Skip to content

Instantly share code, notes, and snippets.

@GrfxGuru
Last active August 29, 2015 14:02
Show Gist options
  • Save GrfxGuru/4542cfd8e6387d39b87d to your computer and use it in GitHub Desktop.
Save GrfxGuru/4542cfd8e6387d39b87d to your computer and use it in GitHub Desktop.
Simple Swift optional example both long and short version.
let numberOfWheels = [“car”: 4, “bike”: 1, "legs" : 0]
let wheelCount: Int? = numberOfWheels[“unicycle”]
// Now to unwrap wheelCount, if wheelCount is nil then
// the if block is never executed
// Long way
if wheelCount == nil {
println(“unicycle wasn’t found”)
} else {
let actualWheelCount = wheelCount!
println(“\(actualWheelCount) wheels”)
}
// Short way
if let actualWheelCount = wheelCount {
println(“\(actualWheelCount) wheels")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment