简体   繁体   中英

Swift: Crash when Printing

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

print(myPath!)

Why does it crash when I'm trying to print this?

The crash is the famous Unexpected found nil while unwrapping ... error. Don't use exclamation marks unless it's guaranteed that the value is not nil .

Either the file does not exist or (most likely) your type (extension) is png not .png

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

However nowadays the URL related API is preferable

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

My simple guess is that myPath is nil, so it crashes at the nil pointer exception. Remove the exclamation mark and use:

print(myPath)

If it prints nil, then you have your answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM