简体   繁体   English

Swift中的存在运算符是什么?

[英]What is the existence operator in Swift?

In Objective C this is a valid line of code 在目标C中,这是有效的代码行

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. 这是检查self.image是否为nil,然后选择left或right值。 In Swift I want to recreate the same line of code. 在Swift中,我想重新创建同一行代码。 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' 但这在我的Swift代码中出现错误时无效,“ UIImage不符合协议LogicValue”

What is the correct Swift code? 什么是正确的Swift代码?

This code works if self.image is an Optional. 如果self.image是可选的,则此代码有效。 There is no reason to have it otherwise because self.image literally cannot be nil. 否则就没有理由,因为self.image的字面值不能为零。

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 . “打开”可选变量image以便您可以访问其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: 如果image是一个隐式展开的可选内容,这也将起作用:

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 因此, self.image必须是计算为truefalse ,在Swift中就是这样的,它符合LogicValue协议

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! 与Obj-C仅仅一个对象的存在等同于true ,Swift需要更多...我们被赋予了可选值,可以用作条件值!

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 因此,如果self.image是可选值,那么您描述的内容就可以工作,如果您看到该错误,听起来好像不是

to round out the answer: 完善答案:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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