Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 633
Ezio Avatar asked Mar 12 '23 03:03

Ezio


1 Answers

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 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.

like image 51
Hamish Avatar answered Mar 19 '23 23:03

Hamish