简体   繁体   中英

Difference between two optional syntaxes in Swift

What is difference between

self?.profile!.id!

and

(self?.profile!.id!)!

XCode converts first to second.

The first one contains self? which means self is optional, leads to let related properties ( profile!.id! in your case) related to the existence of the self which is Optional Chaining :

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil . Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.

To make it more simpler, you could think of id! nullity is also optional, even if you force unwrapping it, because it is related to the existence of self ; If self is nil , profile and id will be also nil implicitly because they are related to the existence of self .

Mentioning: (self?.profile!.id!)! means that the whole value of the chain would be force wrapped.

Note that implementing:

self!.profile!.id!

leads to the same output of

(self?.profile!.id!)!

since self! is force unwrapped, the value of id would not be related to the nullity of self because the compiler assumes that self will always has a value.

However, this approach is unsafe , you should go with optional binding.

First of all you are using too many question and exclamation marks!!!

Practically there is no difference. The result is a forced-unwrapped optional.

Usually Xcode suggests that syntax if the result of the last item of the chaining is a non-optional so the exclamation mark would cause an error for example

text?.count!

Then Xcode suggests

(text?.count)!

but in this case be brave and write

text!.count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM