Why does print(a)
in the following code print nil?
var a:Int?
a? = 4
print(a) //prints nil
var b:Int? = 4
print(b) //prints optional(4)
Shouldn't they both contain 4? Can someone explain it?
In Swift, nil means the absence of a value. Sending a message to nil results in a fatal error. An optional encapsulates this concept. An optional either has a value or it doesn't. Optionals add safety to the language.
Optionals are in the core of Swift and exist since the first version of Swift. An optional value allows us to write clean code with at the same time taking care of possible nil values. If you're new to Swift you might need to get used to the syntax of adding a question mark to properties.
In Swift, you can also use nil-coalescing operator to check whether a optional contains a value or not. It is defined as (a ?? b) . It unwraps an optional a and returns it if it contains a value, or returns a default value b if a is nil.
From the Swift Docs: " Any : The protocol to which all types implicitly conform." And enums are Types, so they conform to the Any protocol. As stated in the comments, nil is not a type (and thus does not conform to Any , it is the absence of a value (and in this case no value has no type).
However there is another data type in Swift called Optional, whose default value is a null value ( nil ). You can use optional when you want a variable or constant contain no value in it. An optional type may contain a value or absent a value (a null value). Non technically, you can think optional as a shoe box.
Optionals say either "there is a value, and it equals x" or "there isn't a value at all". An Optional is a type on its own, actually one of Swift 4’s new super-powered enums. It has two possible values, None and Some (T), where T is an associated value of the correct data type available in Swift 4.
It has two possible values, None and Some (T), where T is an associated value of the correct data type available in Swift 4. Here’s an optional Integer declaration − var perhapsInt: Int?
However there is another data type in Swift called Optional, whose default value is a null value (nil). You can use optional when you want a variable or constant contain no value in it. An optional type may contain a value or absent a value (a null value). Non technically, you can think optional as a shoe box.
The line var a: Int?
declares an optional variable with a nil
value.
The line a? = 4
makes use of optional chaining to assign a value to the variable a
. But if a
is nil
, the assignment isn't done. And this is your case since a
is currently nil
. You simply need a = 4
to assign the value of 4
to the variable a
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With