斯威夫特-NSURL fileURLWithPath没有打开? [英] Swift - NSURL fileURLWithPath not unwrapped?
问题描述
非常简单的一个:我在这两行中都得到了"Value of optional type 'NSURL?' not unwrapped."
,我正试图从现有的Objective-C应用程序之一中进行翻译:
Pretty simple one: I'm getting "Value of optional type 'NSURL?' not unwrapped."
on these two lines, which I'm trying to translate from one of my existing Objective-C apps:
func urlForScene(sceneID:Scene) -> NSURL {
var filename:NSString = "Whatever"
let path = NSBundle.mainBundle().pathForResource(filename, ofType: "m4a")
return NSURL.fileURLWithPath(path)
}
我认为这很容易做到,而path
可能为nil,但是我还没有找到其他让我知道我应该在这里做什么的问题.抱歉,这是一个愚蠢的问题.
I assume this is probably something blindingly simple to do with the possibility of the path
being nil, but I've not found any other questions which let me know what I should be doing here. Apologies if it's a stupid question.
如果未打开NSURL
,我应该打开它吗?我需要以不同的方式拨打fileURLWithPath:
吗?
If the NSURL
isn't unwrapped, should I unwrap it? Do I need to call fileURLWithPath:
differently?
谢谢.
推荐答案
这是问题所在:urlForScene
返回NSURL
,而fileURLWithPath:
返回可选的NSURL?
,(按照文档).
Here's the issue : urlForScene
returns a NSURL
, whereas fileURLWithPath:
returns an optional : NSURL?
, (as per the doc).
因此,问题在于,fileURLWithPath:
可能返回nil
(这就是为什么它返回NSURL?
的原因),并且您返回了非null对象(a NSURL
).
So, the issue is, fileURLWithPath:
might return nil
(this is why it returns a NSURL?
), and you return a non-nil object (a NSURL
).
编译器告诉您解开它,但我想您最好返回NSURL?
并稍后在代码中进行检查.
The compiler tells you to unwrap it, but I'd say you'd better return a NSURL?
and check it later on in your code.
此外,您不应使用NSObject.someInitializer(anObject)
,而应使用NSObject(initializer:anObject)
.根据您的情况,将NSURL.fileURLWithPath(path)
替换为NSURL(fileURLWithPath:path)
.
Plus, you shouldn't use NSObject.someInitializer(anObject)
, but NSObject(initializer:anObject)
. In your case, replace NSURL.fileURLWithPath(path)
by NSURL(fileURLWithPath:path)
.
总而言之,这是工作代码:
To summarize, here's the working code :
func urlForScene(sceneID:Scene) -> NSURL? {
let filename = "Whatever"
let path = NSBundle.mainBundle().pathForResource(filename, ofType: "m4a")
if let path = path {
return NSURL(fileURLWithPath:path)
} else {
return nil
}
/* this would also work, it's a matter of taste :
if let path = NSBundle.mainBundle().pathForResource(filename, ofType: "m4a") {
return NSURL(fileURLWithPath:path)
}
return nil
*/
}
let mySceneURL = urlForScene(someScene)
if let mySceneURL = mySceneURL {
/* use the scene */
} else {
/* the scene couldn't be intialized */
}
这篇关于斯威夫特-NSURL fileURLWithPath没有打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!