“计算属性必须具有显式类型”错误:如何在 Swift 2.x 中列出文件?

Cra*_*lot 0 try-catch ios swift

下面的代码生成一个 Computed property must have an explicit type error.

使用新的try/catchSwift 语法列出文件的正确方法是什么?

do {
       let files = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(docsPath as String) as! [String] {
       print("Found \(files.count) file(s) in \(docsPath):")
}catch{
       print("Error with listing files: \(error)")
}
Run Code Online (Sandbox Code Playgroud)

dfr*_*fri 5

您在不需要{的 try 语句(after ... as! [String])之后添加了一个额外的大括号。这个额外的大括号让 Swift 相信你正在使用计算属性。

卸下支架,您的do-try-catch块应该可以工作:

var docsPath : String = "notavalidpath"
do {
    let files = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(docsPath as String) as! [String]
    print("Found \(files.count) file(s) in \(docsPath):")
}catch{
    print("Error with listing files: \(error)")
}
Run Code Online (Sandbox Code Playgroud)