Ratikanta Patra Ratikanta Patra - 7 months ago 24
Swift Question

Strange behavior of Swift

While playing around with Swift I came across the following scenario:

let testVar: String = "random string"
var myVar: Int! = 0
myVar = Int(testVar)
print("myVar = \(myVar)")


Output:-


myVar = nil


Since I have used
!
mark before
myVar
, isn't it supposed to contain non-nil values all the time?
How come
myVar
is
nil
?
Here is the screenshot of my playground code:

Screenshot

Answer

The '!' indicates forced unwrapping of an optional. However it's type is still optional and therefore can be nil.

(You're just telling the compiler that you guarantee it won't become nil.)

A line like...

let v: Int = myVar

...at the end of your code will get you the crash you expect.


Another example is the way outlets are handled. They are typically defined such as:

@IBOutlet weak var detailDescriptionLabel: UILabel!

Before viewDidLoad is called, it is nil. Again, the '!' is just a promise to the compiler that it won't be used until it contains a valid reference.