将数据附加到字典会导致swift脚本出错

时间:2017-10-01 05:37:46

标签: swift linux

在尝试打印一个有效的JSON对象时,我遇到了一个我无法绕过的错误。当我尝试将信息附加到字典中时,问题就出现了,并且此任务需要扩展字典。

该代码的目的是在 Linux 中为Albert启动器创建扩展模板。

错误是:

./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

代码是:

#! /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)!
    print(JSONString)

} 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() {
      print(jsonStr!)
  }

}

exit(0)

为了重现问题,需要使用以下代码运行代码:ALBERT_OP="QUERY" ./script.swift

  • 在这个特殊情况下我做错了什么?是否与我将其作为脚本运行这一事实有关?

1 个答案:

答案 0 :(得分:0)

我认为您的问题出在try filemgr.contentsOfDirectory(atPath: "~/.snippy"),特别是Swift不会自动扩展路径中的波浪号。您可以使用("~/.snippy" as NSString).expandingTildeInPath

手动执行此操作