我试图阅读一个文本文件使用Swift游乐场与以下
let dirs : String[]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask,true) as? String[] if (dirs != nil) { let directories:String[] = dirs!; let dir = directories[0]; //documents directory let path = dir.stringByAppendingPathComponent(file); //read let content = String.stringWithContentsOfFile(path,encoding: NSUTF8StringEncoding,error: nil) }
这对我有用。我唯一改变的是明确的文件名(这在你的例子中是暗示的) – 也许你在“文件”变量的屏幕外定义中有错字?
let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,true) as? [String] let file = "trial.txt" // My change to your code - yours is presumably set off-screen if let directories = dirs { let dir = directories[0]; //documents directory let path = dir.stringByAppendingPathComponent(file); //read let content = NSString(contentsOfFile: path,usedEncoding: nil,error: nil) // works... }