rgamber
rgamber

Reputation: 5849

Use of an optional value in Swift

While reading the The Swift Programming Language, I came across this snippet:

You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value as optional.

// Snippet #1
var optionalString: String? = "Hello"
optionalString == nil

// Snippet #2     
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
}

Snippet #1 is clear enough, but what is happening in the Snippet #2? Can someone break it down and explain? Is it just an alternative to using an if - else block? what is the exact role of let in this case?

I did read this page, but still a little confused.

Upvotes: 3

Views: 1781

Answers (3)

Thilo
Thilo

Reputation: 262824

if let name = optionalName {
   greeting = "Hello, \(name)"
}

This does two things:

  1. it checks if optionalName has a value

  2. if it does, it "unwraps" that value and assigns it to the String called name (which is only available inside of the conditional block).

Note that the type of name is String (not String?).

Without the let (i.e. with just if optionalName), it would still enter the block only if there is a value, but you'd have to manually/explicitly access the String as optionalName!.

Upvotes: 8

shucao
shucao

Reputation: 2242

String? is a boxed-type, variable optionalName either contains a String value or nothing(that is nil).

if let name = optionalName is an idiom, it unboxes the value out of optionalName and assign it to name. In the meanwhile, if the name is non-nil, the if branch is executed, otherwise the else branch is executed.

Upvotes: 3

Connor
Connor

Reputation: 64684

// this line declares the variable optionalName which as a String optional which can contain either nil or a string. 
//We have it store a string here
var optionalName: String? = "John Appleseed"

//this sets a variable greeting to hello. It is implicity a String. It is not an optional so it can never be nil
var greeting = "Hello!"

//now lets split this into two lines to make it easier. the first just copies optionalName into name. name is now a String optional as well.
let name = optionalName

//now this line checks if name is nil or has a value. if it has a value it executes the if block. 
//You can only do this check on optionals. If you try using greeting in an if condition you will get an error
if  name{
    greeting = "Hello, \(name)"
}

Upvotes: 4

Related Questions