简体   繁体   中英

What is the existence operator in Swift?

In Objective C this is a valid line of code

self.scrollView.contentSize = self.image ? self.image.size : CGSizeZero;

Which is checking if self.image is nil or not, and choosing the left or right value. In Swift I want to recreate the same line of code. Actually it should be exactly the same except without the semicolon

self.scrollView.contentSize = self.image ? self.image.size : CGSizeZero

But this is not valid in my Swift code getting an error, 'UIImage does not conform to protocol LogicValue'

What is the correct Swift code?

This code works if self.image is an Optional. There is no reason to have it otherwise because self.image literally cannot be nil.

The following code is completely valid:

var image : UIImage?
self.scrollView.contentSize = image ? image!.size : CGSizeZero

Note: you must use the "!" to "unwrap" the optional variable image so that you can access its size . This is safe because you just tested before hand that it is not nil.

This would also work if image is an implicitly unwrapped optional:

var image : UIImage!
self.scrollView.contentSize = image ? image.size : CGSizeZero

You are describing the conditional assignment ternary operator ?: , which operates as so:

(condition) ? (assign this value if the condition evaluates to true) : (assign this value if the condition evaluates to false)

therefore, self.image needs to be something that evaluates to true or false , which is the case in Swift for anything that conforms to the LogicValue protocol

unlike Obj-C where the mere presence of an object is equivalent to true , Swift requires a little more... we are given Optional Values that can be used as conditionals!

so what you described works if self.image is an optional value, which it sounds like it is not if you are seeing that error

to round out the answer:

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