Satya Satya - 3 months ago 15
iOS Question

Swift optionals, unwrapping

I am learning the swift syntax and got a little confused with the optional type.
So, from the defination a swift type can not store the null value unless it is explicitly defined as an optional. So, what does the variable in the following line contains when it's declared.

var a:Int (declaring a variable without intializing it working fine in swift 3)

And also when we declare a variable as an optional with a "!",

var optionalSquare: Square! = Square(sideLength: 10, name: "Optional Square")

if we want to use the "optionalSquare" variable, we do not need to unwrap it cause we are sure(I think that is why we are using "!" instead of "?") it does not contain any null value. so why don't we declare it as a normal variable.

Please correct any false statements. Thank you.


what does [var a:Int] contains when it's declared

Nothing. Its value is undefined. Using it before assigning a value is a compilation error. You can declare it without initializing it, but you cannot use it.

This is part and parcel of Swift's philosophy of safety: in C, you could likewise leave a variable uninitialized, and its value would be undefined, but the compiler would not (by default) report error if you use it.

so why don't we declare it as a normal variable.

There's no reason that I can think of to make a local variable an implicitly unwrapped optional. The functionality is intended for properties ("ivars") on structs or classes. You should use them where it's impossible to set the property in the object's init, but it is certain that the value will be present before the object is used.

IBOutlets are probably the canonical use case. Another use that I find helpful is to allow setting a property by calling a method in init.