Swift:打印时崩溃

时间:2017-09-23 19:40:35

标签: ios swift

let myPath = Bundle.main.path(forResource: "Settings", ofType: ".png")

print(myPath!)

为什么我在尝试打印时会崩溃?

2 个答案:

答案 0 :(得分:4)

崩溃是着名的意外发现nil,同时展开...... 错误。除非确保该值不是nil,否则不要使用感叹号。

文件不存在或(很可能)您的类型(扩展名)为png而不是.png

let myPath = Bundle.main.path(forResource: "Settings", ofType: "png") 

但是现在与URL相关的API更可取

let myURL = Bundle.main.url(forResource: "Settings", withExtension: "png") 

答案 1 :(得分:1)

我的简单猜测是myPath为nil,因此它在nil指针异常时崩溃。删除感叹号并使用:

print(myPath)

如果它打印为nil,那么你有答案。