Null object: Difference between revisions

Content added Content deleted
(→‎{{header|Swift}}: Update Swift entry to modern syntax and add another example)
Line 1,671: Line 1,671:


=={{header|Swift}}==
=={{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 deconstruct it, use <code>if let</code>:
To just check if variable is nil, you can use <code>==</code> operator.
<lang swift>if let v = opt {
<lang swift>if maybeInt == nil {
println("There is some value: \(v)")
print("variable is nil")
} else {
} else {
println("There is no value")
print("variable has some 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>
}</lang>