swiftselectoruser-datasender

How do you retrieve userData through a sender in Swift 4?


I can't seem to retrieve sent sender data without getting an error "Value of 'Any' has no subscripts".

It seems like a new error since this is the way I've always done it, and I can't find information on how to fix it.

let selector = #selector(self.updatePoint(sender:))
Timer.scheduledTimer(timeInterval: 1,
                     target: self,
                     selector: selector,
                     userInfo: ["index": 3, "tempPoint": tempPoints[3]],
                     repeats: false)

@objc func updatePoint(sender: Timer) {

    guard let index = sender.userInfo?["index"] as? Int else {return} // Error: Value of 'Any' has no subscripts
    ...
}

Solution

  • userInfo is of type Any you need to cast it first to [String:Any]

    guard let info = sender.userInfo as? [String:Any],let index = info["index"] as? Int else {return}