Null object: Difference between revisions

→‎{{header|Swift}}: Update Swift entry to modern syntax and add another example
(→‎{{header|Swift}}: Update Swift entry to modern syntax and add another example)
Line 1,671:
 
=={{header|Swift}}==
Swift has <code>Optional<T></code> type, where <code>nil</code> means a lack of value.
The closest thing in Swift are optional types.
<code>T?</code> is syntactic sugar for <code>Optional<T></code>.
<lang swift>var opt : Int? = nil // use "nil" to represent no value
<lang swift>let maybeInt: Int? = nil</lang>
opt = 5 // or simply assign a value to the optional type</lang>
To deconstructjust itcheck if variable is nil, you can use <code>if let==</code>: operator.
<lang swift>if let vmaybeInt == optnil {
printlnprint("Therevariable is some value: \(v)nil")
} else {
printlnprint("Therevariable ishas nosome value")
}</lang>
 
Usually you want to access the value after checking if it's nil. To do that you use <code>if let</code>
<lang swift>if let certainlyInt = maybeInt {
print("variable has value \(certainlyInt)")
} else {
print("variable is nil")
}</lang>
 
Anonymous user