Create a folder with Swift [duplicate]

為{幸葍}努か 提交于 2019-12-12 03:23:46

问题


I'm trying to use NSFileManager's method createDirectoryAtPath:withIntermediateDirectories:attributes:error: in Swift.

The problem is that I have no idea what this function throws in case of error. Is this documented anywhere? If yes, where?


回答1:


When the Swift docs says a function throws, they mean that it throws an NSError.

Consider the following do-try-catch flow:

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]

do {
    try NSFileManager.defaultManager().createDirectoryAtPath(documentsPath, withIntermediateDirectories: false, attributes: nil)
} catch {
    print(error)
    print(error.dynamicType)
}

createDirectoryAtPath will fail because the documents directory already exists. Logging the dynamicType of the error shows that it is in fact an NSError object:

Error Domain=NSCocoaErrorDomain Code=516 "The file “Documents” couldn’t be saved in the folder “35B0B3BF-D502-4BA0-A991-D07568AB87C6” because a file with the same name already exists." UserInfo={NSFilePath=/Users/jal/Library/Developer/CoreSimulator/Devices/E8A35774-C9B7-42F0-93F1-8103FBBC7118/data/Containers/Data/Application/35B0B3BF-D502-4BA0-A991-D07568AB87C6/Documents, NSUnderlyingError=0x7fa88bd14410 {Error Domain=NSPOSIXErrorDomain Code=17 "File exists"}}

NSError


来源:https://stackoverflow.com/questions/34093642/create-a-folder-with-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!