iOS8,Swift:fileURLWithPath - 缺少参数错误的参数 [英] iOS8, Swift: fileURLWithPath - missing argument for parameter error

查看:70
本文介绍了iOS8,Swift:fileURLWithPath - 缺少参数错误的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下方法将子目录附加到文档目录:

I am trying to append subdirectory to documents directory using method:

class func fileURLWithPath(path: String) -> NSURL?`

代码:

let applicationDocumentsDirectory:String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let storesDirectory:NSURL = NSURL.fileURLWithPath(applicationDocumentsDirectory).URLByAppendingPathComponent("Stores")

出现错误

调用中缺少参数isDirectory"的参数.

missing argument for parameter 'isDirectory' in call.

我不太明白,为什么编译器需要这个参数?界面里没提到?

I don't really get it, why compiler requires this parameter? It isn't mentioned in the interface?

提前Thnanx

推荐答案

问题是当链中存在可选项时,您正在尝试链接方法.

The problem is that you're trying to chain methods when there are optionals in the chain.

NSURL.fileURLWithPath(applicationDocumentsDirectory) 返回 NSURL? 类型.当您尝试对其执行方法 URLByAppendingPathComponent 时,它会引发编译器错误.

NSURL.fileURLWithPath(applicationDocumentsDirectory) returns NSURL? type. When you try to execute method URLByAppendingPathComponent on it, it throws a compiler error.

我知道编译器错误与真正的原因完全无关,这有点糟糕,但这只是当前 Swift 版本的一个优点.

I know it's kind of sucks that the compiler error is totally unrelated to the real cause, but it's just a beauty of current Swift version.

使用 ! 解包,它会正常工作:

Use ! to unwrap and it's gonna work properly:

let storesDirectory:NSURL = 
NSURL.fileURLWithPath(applicationDocumentsDirectory)!
     .URLByAppendingPathComponent(NFConstants.NFCoreDataStringIdentifiers.CoreDataStoresPathComponent.rawValue)

当然,强制解开可选项可能会导致崩溃,所以最好使用 if let 习惯用法:

Of course force unwrapping the optional is potentially crashy, so even better use if let idiom:

if let baseUrl = NSURL.fileURLWithPath(applicationDocumentsDirectory) {
    let storeURL = baseUrl.URLByAppendingPathComponent(NFConstants.NFCoreDataStringIdentifiers.CoreDataStoresPathComponent.rawValue)
}

这篇关于iOS8,Swift:fileURLWithPath - 缺少参数错误的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆