lf_araujo lf_araujo - 3 years ago 174
Swift Question

Appending data into dictionary causes error in swift script

On trying to pretty print a valid JSON object I got stuck in an error that I am unable to circumvent. The problem started when I tried to append information into a dictionary and a extension for Dictionary was necessary for this task.

The aim of the code is to create an extension template for Albert launcher in Linux.

The error is:

./org.albert.extension.external.snippy.swift:10:21: warning: no calls to throwing functions occur within 'try' expression
let jsonS = try String(data: jsonD, encoding: String.Encoding.utf8)
fatal error: Error raised at top level: The operation could not be completed: file /home/buildnode/jenkins/workspace/oss-swift-4.0-package-linux-ubuntu-16_10/swift/stdlib/public/core/ErrorType.swift, line 187
Current stack trace:
0 libswiftCore.so 0x00007f089c352bc0 _swift_stdlib_reportFatalErrorInFile + 221

And the code is:

#! /usr/bin/swift
import Glibc
import Foundation

let albert_op = ProcessInfo.processInfo.environment["ALBERT_OP"]

extension Dictionary where Key == String {
func toPrettyJSON() throws -> String? {
let jsonD = try JSONSerialization.data(withJSONObject: self,options: [.prettyPrinted])
let jsonS = try String(data: jsonD, encoding: String.Encoding.utf8)
return jsonS

if albert_op == "METADATA" {
let metadata : [String: Any] = [
"iid": "org.albert.extension.external/v2.0",
"name": "snippets",
"version": "0.1",
"author": "lf-araujo",
"dependencies": [],
"trigger": "snip "

let jsonData = try JSONSerialization.data(withJSONObject: metadata)
let JSONString = String(data: jsonData, encoding: String.Encoding.utf8)!

} else if albert_op == "QUERY" {
let filemgr = FileManager.default
let filelist = try filemgr.contentsOfDirectory(atPath: "~/.snippy")

func buildItem(name: String) -> [String:Any] {
let action : [String: Any] = [
"name": name
return action

var items : [String: Any] = [:]
items["items"] = filelist.map { buildItem(name: $0) }

if let jsonStr = try? items.toPrettyJSON() {



In order to reproduce the problem, one needs to run the code with:
ALBERT_OP="QUERY" ./script.swift

  • What am I doing wrong in this particular case? Is it related to the fact that I am running it as a script?

Answer Source

I think your issue is at try filemgr.contentsOfDirectory(atPath: "~/.snippy"), specifically the fact that Swift doesn't automatically expand tildes in paths. You can manually do it with ("~/.snippy" as NSString).expandingTildeInPath

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download