The Swift Programming Language guide has the following example:
class Person {
let name: String
init(name: String) { self.name = name }
var apar
ASK YOURSELF
person?
have an apartment
member/property? ORperson
have an apartment
member/property?If you can't answer this question, then continue reading:
To understand you may need super-basic level of understanding of Generics. See here. A lot of things in Swift are written using Generics. Optionals included
The code below has been made available from this Stanford video. Highly recommend you to watch the first 5 minutes
enum Optional{
case None
case Some(T)
}
let x: String? = nil //actually means:
let x = Optional.None
let x :String? = "hello" //actually means:
let x = Optional.Some("hello")
var y = x! // actually means:
switch x {
case .Some(let value): y = value
case .None: // Raise an exception
}
let x:String? = something
if let y = x {
// do something with y
}
//Actually means:
switch x{
case .Some(let y): print)(y) // or whatever else you like using
case .None: break
}
when you say var john: Person?
You actually mean such:
enum Optional{
case .None
case .Some(Person)
}
Does the above enum have any property named apartment
? Do you see it anywhere? It's not there at all! However if you unwrap it ie do person!
then you can ... what it does under the hood is : Optional
Had you defined var john: Person
instead of: var john: Person?
then you would have no longer needed to have the !
used, because Person
itself does have a member of apartment
As a future discussion on why using !
to unwrap is sometimes not recommended see this Q&A