Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional chaining used in left side of assignment in Swift

What does it mean when optional chaining is used in the left side of the assignment statement? Will the app crash if the optional variable is nil?

e.g.

// cell is a UITableViewCell
cell.textLabel?.text = "Test"
like image 289
Boon Avatar asked Mar 23 '15 22:03

Boon


People also ask

Which is used for optional chaining in Swift?

You specify optional chaining by placing a question mark ( ? ) after the optional value on which you wish to call a property, method or subscript if the optional is non- nil . This is very similar to placing an exclamation point ( ! ) after an optional value to force the unwrapping of its value.

What is the use of optional chaining?

Optional chaining (?.) The optional chaining ( ?. ) operator accesses an object's property or calls a function. If the object is undefined or null , it returns undefined instead of throwing an error.

What is difference between optional binding and optional chaining in Swift?

Optional binding allows an entire block of logic to happen the same way every time. Multiple lines of optional chaining can make it unclear exactly what is going to happen and could potentially be subject to race-conditions causing unexpected behavior.

How the optional type is denoted in Swift?

An optional in Swift is basically a constant or variable that can hold a value OR no value. The value can or cannot be nil. It is denoted by appending a “?” after the type declaration.


3 Answers

Sort of like a short-circuiting && operator that stops when it reaches the first false value, optional chaining will stop when it hits the first nil value.

So in an extreme case like container?.cell?.textLabel?.text = "foo", any of container, cell, or textLabel could be nil. If any of them are, that statement is effectively a no-op. Only if the whole chain is non-nil will the assignment happen.

like image 68
gregheo Avatar answered Nov 07 '22 08:11

gregheo


For the sake of completeness, in addition to @gregheo answer:

The unwrapped value of an optional-chaining expression can be modified, either by mutating the value itself, or by assigning to one of the value’s members. If the value of the optional-chaining expression is nil, the expression on the right hand side of the assignment operator is not evaluated.

Quoted from "Optional-Chaining Expression"

like image 25
rintaro Avatar answered Nov 07 '22 06:11

rintaro


It will just act as an optional, you can set it as a string or nil. Neither of them will crash the app unless you unwrap your variable without catching if it is nil, when it is nil. If anything in your chain is an optional, your whole chain is (or at least everything after the optional)

like image 1
milo526 Avatar answered Nov 07 '22 08:11

milo526