[英]OR condition for optional binding?
I've seen in Swift 3.1
documentation that you can include several optional bindings in an if
statement separated by commas, and that it behaves like an AND
operator. 我在Swift 3.1
文档中看到,您可以在以逗号分隔的if
语句中包含多个可选绑定,并且其行为类似于AND
运算符。
Let's say that I have two optional properties and I'd like to check which of them (or both) is/are not nil
, unwrap the non-nil one(s), and then execute a block of code. 假设我有两个可选属性,我想检查其中的一个(或两个)都不为nil
,解开非nil的那些,然后执行一段代码。 Using this: 使用这个:
if let = property1, let = property2 {
// Some task to do with unwrapped property
}
only executes the if
statement block if both properties are unwrapped ( AND
condition). 仅当两个属性都已解包( AND
条件)时,才执行if
语句块。 But for me, it would be enough to have at least one of those properties being non-nil to execute the code in the if
statement block ( OR
condition). 但是对我来说,至少要使这些属性中的至少一个为非零,以便在if
语句块( OR
条件)中执行代码就足够了。 But if I do like this: 但是,如果我这样做:
if property1 != nil || property2 != nil {
// Some task to do with non-nil property
}
But then I don't have the unwrapped value of the non-nil property. 但是然后我没有non-nil属性的展开值。 I'd like to have the unwrapped value available in the if
statement block of code to avoid optional chaining there. 我想在代码的if
语句块中提供可用的解包值,以避免在那里出现可选的链接。
Which would be the best practice and most compact way to achieve this? 哪种方法是实现这一目标的最佳实践和最紧凑的方法?
How about this. 这个怎么样。
if let property = property1 ?? property2 {
// non nil property (any one of the two)
}
if property1
and property2
both have values property1
gets the precedence. 如果property1
和property2
都具有值,则property1
获得优先级。
Unfortunately I don't think this is possible in a single line (like if let x = y || let z = a {}
). 不幸的是,我认为这不可能在一行中实现(例如, if let x = y || let z = a {}
)。 Logically it wouldn't make sense, because you would end up in a state where both variables would remain optional (if either is unwrapped, you don't know which is unwrapped or if both are). 从逻辑上讲,这是没有意义的,因为您最终将处于两个变量都将保持可选状态的状态(如果其中一个已解包,则您不知道哪个已解包,或者两个都不解包)。 I think you'll need to take some other approach to this problem. 我认为您需要采取其他方法来解决此问题。 I think the simplest form would be something like 我认为最简单的形式是
if let unwrappedProperty1 = property1 {
handleProperty(unwrappedProperty1)
} else if let unwrappedProperty2 = property2 {
handleProperty(unwrappedProperty2)
}
or you could do something like 或者你可以做类似的事情
if let unwrappedProperty = property1 ?? property2 {
handleProperty(unwrappedProperty)
}
which would give priority to property1 这将优先考虑property1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.