swift - Why Implicitly unwrapped optional was not assigned? -
in following code, why 5 not assigned "somevar" ?
class viewcontroller: uiviewcontroller { var somevar : int? override func viewdidload() { super.viewdidload() somevar! = int(5) // why 5 not assigned somevar here } } background:
somevar declared optional variable means if variable nil command using variable ignored.
example:
class viewcontroller: uiviewcontroller { var somevar : int? override func viewdidload() { super.viewdidload() somevar? = 5 // command ignored bcz somevar nil } } to forcefully execute command on our own risk use "implicitly unwrapped optional" sure command executed, in case following line executed
somevar! = 5 fatal error: unexpectedly found nil while unwrapping optional value
when line executed, why "5" not assigned "somevar" instead fatal error occurs?
class viewcontroller: uiviewcontroller { var somevar : int? override func viewdidload() { super.viewdidload() somevar! = 5 } }
when something! (emphasis on ! mark), "force reading" (force unwrapping) optional.
that above code tries read something before assigning new value.
since something nil, code explodes.
to illustrate:
var somevar: int? print(somevar!) // code explodes! 💥 print(somevar) // output "nil" somevar = 5 print(somevar!) // output "5" print(somevar) // output "optional(5)" as @leodabus stated, covered in apple's awesome swift book.
(btw book! 📘❤️)
Comments
Post a Comment