"计算属性必须具有明确的类型"错误:如何在Swift 2.x中列出文件?

时间:2016-01-10 02:41:51

标签: ios swift try-catch

以下代码生成Computed property must have an explicit type error.

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

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)")
}

1 个答案:

答案 0 :(得分:3)

您在不需要的try语句({之后)之后添加了一个额外的大括号... 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)")
}