ios - 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 because looking @ address fields? right way use switch statement?
under hood, switch statement uses pattern matching operator (~=) in order define comparisons can do. in case, it's using this version:
@warn_unused_result public func ~=<t : equatable>(a: t, b: t) -> bool this takes 2 equatable arguments of same concrete type. in switch statement, each case passed a, , statement switch on passed b. bool returns defines whether case should triggered, in case return value of a == b.
uitextfield inherits nsobject, conforms equatable via isequal. therefore valid use 2 uitextfields operator, , therefore valid use them in switch.
as base implementation, isequal checks pointer equality. therefore switch statement indeed checking given uitextfield exact same instance given case.
you think doing this:
if textfield == statefield { print("editing state") } else if textfield == countryfield { print("editing country") } else { // 'default' case } which doing (in case of nsobject inherited classes):
if textfield.isequal(statefield) { print("editing state") } else if textfield.isequal(countryfield) { print("editing country") } else { // 'default' case } using switch here great usage – makes code clearer chaining lots of if & else if statements together.