Optional Value In Swift

Posted by on Mar 22, 2016 in Swift | No Comments

An optional provides a variable that can be assigned to contain a value, or left or assigned as nil. The pattern below creates and optional variable (note the ?), assigns it a value, then checks if that value has been assigned.

//create optional 
var optionalName: String?
//assign value
optionalName = "Billy"
// check for value
if let name = optionalName {
    greeting = "Hello, \(name)"
}

Email this to someoneTweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on StumbleUponShare on RedditDigg this

Leave a Reply