Alexis Coquard Alexis Coquard - 1 month ago 36
iOS Question

How to get identity of sender in swift 3

Since swift 3 some AnyObject type has been set to Any.
However I can't seem to access the sender tag.

I first had

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (saveButton === sender) {
let name = nameField.text ?? ""
program = Program(id: -1, name: name, type: capsulesTypes![typeSelected], planning: planningString, date: timePicker.date.timeIntervalSince1970, intensity: Int(intensitySlider.value), enabled: false)
sendProgramToAPI(program!)
}


It worked well in Swift 2 when sender was an AnyObject. However now the condition is always wrong. So I tried using tag.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (saveButton.tag == sender.tag) {
let name = nameField.text ?? ""
program = Program(id: -1, name: name, type: capsulesTypes![typeSelected], planning: planningString, date: timePicker.date.timeIntervalSince1970, intensity: Int(intensitySlider.value), enabled: false)
sendProgramToAPI(program!)
}


But I have an error saying Any? has no member tag. The tag is basically lost in space and time forevermore.

Any idea to identify the sender somehow ?

Answer

You need to cast the sender's type. If you are sure that the sender is always a UIButton, you can do the following:

if saveButton.tag == (sender as! UIButton).tag {

Or, if you'd rather not use the tag property, this should work too:

if saveButton == (sender as! UIButton) {

Hope that helps :)

Comments