如何在 Swift 中找到 NSDocumentDirectory? [英] How to find NSDocumentDirectory in Swift?
问题描述
我正在尝试使用代码获取 Documents 文件夹的路径:
I'm trying to get path to Documents folder with code:
var documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory:0,NSSearchPathDomainMask:0,true)
但 Xcode 给出错误:Cannot convert expression's type 'AnyObject[]!'输入'NSSearchPathDirectory'
but Xcode gives error: Cannot convert expression's type 'AnyObject[]!' to type 'NSSearchPathDirectory'
我正在尝试了解代码中的问题.
I'm trying to understand what is wrong in the code.
推荐答案
显然,编译器认为 NSSearchPathDirectory:0
是一个数组,当然它期望的类型是 NSSearchPathDirectory
代替.当然不是有用的错误消息.
Apparently, the compiler thinks NSSearchPathDirectory:0
is an array, and of course it expects the type NSSearchPathDirectory
instead. Certainly not a helpful error message.
但至于原因:
首先,您混淆了参数名称和类型.看一下函数定义:
First, you are confusing the argument names and types. Take a look at the function definition:
func NSSearchPathForDirectoriesInDomains(
directory: NSSearchPathDirectory,
domainMask: NSSearchPathDomainMask,
expandTilde: Bool) -> AnyObject[]!
directory
和domainMask
是名称,您使用的是类型,但无论如何您应该将它们保留在函数之外.它们主要用于方法.- 另外,Swift 是强类型的,所以你不应该只使用 0.而是使用枚举的值.
- 最后,它返回一个数组,而不仅仅是一个路径.
directory
anddomainMask
are the names, you are using the types, but you should leave them out for functions anyway. They are used primarily in methods.- Also, Swift is strongly typed, so you shouldn't just use 0. Use the enum's value instead.
- And finally, it returns an array, not just a single path.
这样我们就可以了(针对 Swift 2.0 进行了更新):
So that leaves us with (updated for Swift 2.0):
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
对于 Swift 3:
and for Swift 3:
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
这篇关于如何在 Swift 中找到 NSDocumentDirectory?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!