Skip to content

Instantly share code, notes, and snippets.

@goooooouwa
Last active August 29, 2015 14:05
Show Gist options
  • Save goooooouwa/20a93a0049341d1aebc5 to your computer and use it in GitHub Desktop.
Save goooooouwa/20a93a0049341d1aebc5 to your computer and use it in GitHub Desktop.
example usage of optional type in swift
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