Last active
August 29, 2015 14:05
-
-
Save goooooouwa/20a93a0049341d1aebc5 to your computer and use it in GitHub Desktop.
example usage of optional type in swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var exampleDictionary = ["foo":1,"bar":2] | |
// an optional type means its value can either be some certain type or nothing at all( nil) | |
var optionalTypeVariable: Int? = exampleDictionary["someUncertainValue"] | |
// calling optionalTypeVariable will either return an integer or a nil, so you should normally check it’s value before actually using it | |
if optionalTypeVariable == nil { | |
println("The value of optionalTypeVariable is nil") | |
} else { | |
// calling optionalTypeVariable! will always return an integer, if optionalTypeVariable is in fact nil, then an assertion will be triggered. | |
let IntegerConstant: Int = optionalTypeVariable! | |
println("The value of optionalTypeVariable is /(IntegerConstant)") | |
} | |
// short version | |
if let IntegerConstant = optionalTypeVariable { | |
println("The value of optionalTypeVariable is /(IntegerConstant)") | |
} else { | |
println("The value of optionalTypeVariable is nil") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment