Pete Pete - 1 month ago 15
Swift Question

How to Identify Delegating Object

I am using delegation and am using the same class in two different ways.

protocol ColorSwitchDelegate {
func colorSwitched(picker: ColorSwitch, color: ColorChoice)
}

class ColorSwitch: UIView {
var delegate: ColorSwitchDelegate?

func doSomething() {
delegate?.colorSwitched(picker: self, color: color)
}
}

class SettingsViewController: UIViewController, ColorSwitchDelegate {

@IBOutlet weak var myView1: ColorSwitch!
@IBOutlet weak var myView2: ColorSwitch!

func viewWillAppear(_ animated: Bool) {

myView1.delegate = self
myView2.delegate = self
}



func colorSwitched(picker: ColorSwitch, color: ColorChoice) {
// I want to find out if myView1 or myView2 is the delegating object
}
}


I want to identify which view (myView1 or myView2) is the delegator. I could add a tag in the ColorSwitch class but this seems inelegant. Is there a better way?

Answer

You can directly check in colorSwitched using identity opeartor === which test whether two object references both refer to the same object instance.

func colorSwitched(picker: ColorSwitch, color: ColorChoice) {
   if picker === self.myView1 { 

     //myView1
    } else {

     //myView2

    } 

}