Swift:打印时崩溃

Joh*_*ith 0 ios swift

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

print(myPath!)
Run Code Online (Sandbox Code Playgroud)

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

vad*_*ian 5

崩溃是在展开...错误时发现nil的著名的意外。除非可以保证不使用感叹号,否则请不要使用感叹号nil

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

let myPath = Bundle.main.path(forResource: "Settings", ofType: "png") 
Run Code Online (Sandbox Code Playgroud)

但是,如今,与URL相关的API更可取

let myURL = Bundle.main.url(forResource: "Settings", withExtension: "png") 
Run Code Online (Sandbox Code Playgroud)

  • 有人可能会争辩说,您应该强制解包`Bundle.main.url(或路径)的结果,因为您正试图加载您希望存在的文件。如果文件不存在,则说明该项目(或类型)存在安装问题,您希望该应用立即崩溃,以便您可以解决该项目(或错别字)的问题。 (3认同)