或可选绑定的条件?
OR condition for optional binding?
我在 Swift 3.1
文档中看到,您可以在 if
语句中包含多个可选绑定,用逗号分隔,并且它的行为类似于 AND
运算符。
假设我有两个可选属性,我想检查它们中的哪一个(或两者)is/are 而不是 nil
,展开非 nil 的,并且然后执行一段代码。使用这个:
if let = property1, let = property2 {
// Some task to do with unwrapped property
}
仅在两个属性都展开(AND
条件)时才执行 if
语句块。但对我来说,只要这些属性中至少有一个非零就足以执行 if
语句块(OR
条件)中的代码。但如果我这样做:
if property1 != nil || property2 != nil {
// Some task to do with non-nil property
}
但是我没有非零 属性 的展开值。我想在 if
语句块中提供未包装的值,以避免在那里进行可选链接。
实现此目标的最佳做法和最简洁的方法是什么?
这个怎么样。
if let property = property1 ?? property2 {
// non nil property (any one of the two)
}
如果property1
和property2
都有值property1
获得优先权。
不幸的是,我不认为这在一行中是可能的(比如 if let x = y || let z = a {}
)。从逻辑上讲,这是没有意义的,因为您最终会处于两个变量都保持可选的状态(如果其中一个被展开,您不知道哪个被展开或两个都被展开)。我认为您需要采取其他方法来解决这个问题。我认为最简单的形式是
if let unwrappedProperty1 = property1 {
handleProperty(unwrappedProperty1)
} else if let unwrappedProperty2 = property2 {
handleProperty(unwrappedProperty2)
}
或者你可以做类似的事情
if let unwrappedProperty = property1 ?? property2 {
handleProperty(unwrappedProperty)
}
哪个会优先属性1
我在 Swift 3.1
文档中看到,您可以在 if
语句中包含多个可选绑定,用逗号分隔,并且它的行为类似于 AND
运算符。
假设我有两个可选属性,我想检查它们中的哪一个(或两者)is/are 而不是 nil
,展开非 nil 的,并且然后执行一段代码。使用这个:
if let = property1, let = property2 {
// Some task to do with unwrapped property
}
仅在两个属性都展开(AND
条件)时才执行 if
语句块。但对我来说,只要这些属性中至少有一个非零就足以执行 if
语句块(OR
条件)中的代码。但如果我这样做:
if property1 != nil || property2 != nil {
// Some task to do with non-nil property
}
但是我没有非零 属性 的展开值。我想在 if
语句块中提供未包装的值,以避免在那里进行可选链接。
实现此目标的最佳做法和最简洁的方法是什么?
这个怎么样。
if let property = property1 ?? property2 {
// non nil property (any one of the two)
}
如果property1
和property2
都有值property1
获得优先权。
不幸的是,我不认为这在一行中是可能的(比如 if let x = y || let z = a {}
)。从逻辑上讲,这是没有意义的,因为您最终会处于两个变量都保持可选的状态(如果其中一个被展开,您不知道哪个被展开或两个都被展开)。我认为您需要采取其他方法来解决这个问题。我认为最简单的形式是
if let unwrappedProperty1 = property1 {
handleProperty(unwrappedProperty1)
} else if let unwrappedProperty2 = property2 {
handleProperty(unwrappedProperty2)
}
或者你可以做类似的事情
if let unwrappedProperty = property1 ?? property2 {
handleProperty(unwrappedProperty)
}
哪个会优先属性1