新开了 K08-RandomColorization ,刚写了一行代码:
let bgMusic = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Ecstasy", ofType: "mp3")) 然后就报了一个error:
Value of optional type ‘String’ not unwrapped;did you mean to use ‘!’ or ‘?’?”
这里 寻得一个不错的答案,翻译及理解如下:
首先,这行代码使用到了 可选链式调用(Optional Chaining) 这个家伙。用人话说,就是 NSBundle.mainBundle().pathForResource("Ecstasy", ofType: "mp3") 要么就是一个 String ,要么就是一个 nil 。
但是,显然 NSURL 的 fileURLWithPath: 方法不会接受 nil ,只会接受 String 类型的参数,所以编译器就把这个error报出来了。(可以做一个实验,直接写 let bgMusic = NSURL(fileURLWithPath: nil) ,就会发现报 Nil is not compatible with expected argument type ‘String’ 的error。)
解决办法是强制展开 NSBundle.mainBundle().pathForResource("Ecstasy", ofType: "mp3") ,即添加一个 ! :
let bgMusic = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Ecstasy", ofType: "mp3")!) 但是,如果所需文件不存在就会导致一个运行时的error,直接挂掉。所以,通常来说最好是用一个可选绑定把它包起来:
if let file = NSBundle.mainBundle().pathForResource("aaa", ofType: "mp3") { let bgMusic = NSURL(fileURLWithPath: file) NSLog(bgMusic.absoluteString) } 这样就可以保证 fileURLWithPath: 只有在文件不为空时才被调用了。完美~