“计算属性必须有一个明确的types”错误:如何在Swift 2.x中列出文件?
下面的代码生成一个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)") }
你已经添加了一个额外的大括号{
在你的try语句之后(在... as! [String]
之后... 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)") }