Swift: Why does switching text fields work?

For instance:

func textFieldDidBeginEditing(textField: UITextField) {
    switch textField {
    case stateField:
        print("editing state")
    case countryField:
        print("editing country")
    default:
        break
    }
}

Is it because it is looking for an address for these fields? Is it correct to use the switch statement?

+4
source share
1 answer

Under the hood, the operator switchuses the pattern matching operator ( ~=) to determine the comparisons that it can perform. In your case, it uses this version :

@warn_unused_result
public func ~=<T : Equatable>(a: T, b: T) -> Bool

Equatable . switch a, b. Bool , , a == b.

UITextField NSObject, Equatable isEqual. 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.

+7

All Articles