例如:
func textFieldDidBeginEditing(textField: UITextField) {
switch textField {
case stateField:
print("editing state")
case countryField:
print("editing country")
default:
break
}
}
是因为它正在查看这些字段的地址吗?这是使用 switch 语句的正确方法吗?
最佳答案
在幕后,switch
语句使用 pattern matching operator (~=
) 来定义它可以做的比较。在您的情况下,它使用 this version :
@warn_unused_result
public func ~=<T : Equatable>(a: T, b: T) -> Bool
这需要两个相同具体类型的 Equatable
参数。在 switch 语句中,每个 case 都被传递到 a
中,而要打开的语句被传递到 b
中。它返回的 Bool
定义了是否应该触发 case,在这种情况下它将返回 a == b
的值。
UITextField
继承自NSObject
,通过isEqual
符合Equatable
。因此,为该运算符使用两个 UITextFields
是有效的,因此在 switch
中使用它们也是完全有效的。
作为其基本实现,isEqual
仅检查指针是否相等。因此,您的 switch 语句确实只是检查您给定的 UITextField
是否与给定案例完全相同。
你也可以这样想:
if textField == stateField {
print("editing state")
} else if textField == countryField {
print("editing country")
} else {
// 'default' case
}
这就是这样做的(在 NSObject
继承类的情况下):
if textField.isEqual(stateField) {
print("editing state")
} else if textField.isEqual(countryField) {
print("editing country")
} else {
// 'default' case
}
在这里使用 switch
是一个很好的用法 - 它使您的代码比将许多 if
和 else if
语句链接在一起更清晰。
关于ios - Swift:为什么切换文本字段有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37579005/