如何在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给出错误:无法将表达式的类型'AnyObject []!'转换为输入'NSSearchPathDirectory'
but xcode gives error: Cannot convert expression's type 'AnyObject[]!' to type 'NSSearchPathDirectory'
我试图理解代码中的错误?
I'm trying to understand what is wrong in 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[]!
-
目录
和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:
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
这篇关于如何在swift中找到NSDocumentDirectory?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!