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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With