Ezio Ezio - 6 months ago 14
iOS Question

Swift: Why does switching over textfields work?

For example:

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


Is it because its looking at address for those fields? Is this a right way to use switch statement?

Answer

Under the hood, the switch statement uses the pattern matching operator (~=) in order to define the comparisons it can do. In your case, it's using this version:

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

This takes two Equatable arguments of the same concrete type. In the switch statement, each case is passed into a, and the statement to switch on is passed into b. The Bool it returns defines whether the case should get triggered, in this case it will return the value of a == b.

UITextField inherits from NSObject, which implicitly conforms to Equatable via isEqual. Therefore it is valid to use two UITextFields for this operator, and therefore perfectly valid to use them in a switch.

As its base implementation, isEqual just checks for pointer equality. Therefore your switch statement is indeed simply checking that your given UITextField is the exact same instance as a given case.

You could also think about as doing this:

if textField == stateField {
    print("editing state")
} else if textField == countryField {
    print("editing country")
} else {
    // 'default' case
}

Which is just doing this (in the case of NSObject inherited classes):

if textField.isEqual(stateField)  {
    print("editing state")
} else if textField.isEqual(countryField) {
    print("editing country")
} else {
    // 'default' case
}

Using a switch here is great usage – it makes your code much clearer than chaining lots of if & else if statements together.