ximmyxiao
ximmyxiao

Reputation: 2801

Why don't you need to unwrap an optional type value when being set?

Does it mean that the set operation doesn't read the actual value of the Optional, so it doesn't need to be unwrapped?

var str = "Hello, playground"

class Base{
    var name:String?
};

var obj = Base()
obj.name = "hello" //this line don't need unwrapping first

Upvotes: 0

Views: 1496

Answers (2)

vacawama
vacawama

Reputation: 154513

An optional is a box. The box can either contain nothing (which is called nil) or it can contain something of a specific type (a String in your example). You unwrap an optional to access the value inside in the box.

When you are assigning a value to an optional, you just need to assign the value to the box itself. There is no need to unwrap anything, because you are just putting a value into the box. Swift either empties the box, if you assign nil, or it wraps the value by putting it into the box.

Unwrapping is for accessing a value that is already in the box.


Answering your question from a comment on another answer...

But why Optional binding don't need unwrapping? i think i if let constantName = some Optional is kind of assignment too

Optional binding is an unwrapping operation and an assignment operation. It says "if there is a value inside the box, assign it to this new variable and enter the then clause, otherwise proceed to the else clause if it exists".

var optionalValue: String? = "hello"

if let value = optionalValue {
    // value is the contents of the box, it has type String
    print("value is \(value)")
} else {
    // the optional binding failed because the box is empty
    print("optionalValue is nil")
}

Upvotes: 1

LinusG.
LinusG.

Reputation: 28892

When you set an Optional property, you do not have to unwrap it.
Unwrapping is required only when assigning an optional value to a non-optional property:

var name: String = "" // non-optional
var str: String?

// this will not compile, because you need to unwrap str first
name = str

// this will compile, because we're providing a default value
name = str ?? ""

// this will also compile, because name is not an optional
// it would still compile if name was optional, because str is optional too
str = name

Upvotes: 1

Related Questions