Ratikanta Patra Ratikanta Patra - 9 months ago 28
Swift Question

Strange behaviour of swift

While playing around with swift I cam across the following scenario

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

myVar = nil

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


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.