0

My Swift code looks like this:

class SystemClass {
    public init() {}
    func setXYZ(xyz: Float32) {
        // do something
    }
}

let callME: class = class()
class class {
  public init() {}
  func functionXYZ() {  
    Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(SystemClass().setXYZ(xyz: 1.0)), userInfo: nil, repeats: true) // error code
  }
}

callME.functionXYZ()

I'd like to call the 'functionXYZ' and this is already working fine but calling the setXYZ function leads to errors because the selector failed.

How to edit the selector:

#selector(SystemClass().setXYZ(xyz: 1.0))

to call the setXYZ function with the given parameter?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • You can't pass param this way, the selector awaits for the signature, not with params. You could use the `userInfo` instead. – Larme Jan 04 '18 at 19:40
  • Please don't rollback useful edits. Do not use irrelevant tags. Do not put tags and needless commentary in your title. I also fixed other formatting as well. No need to undo all of those useful and appropriate changes. – rmaddy Jan 04 '18 at 19:56

1 Answers1

1

EDIT: Updating to include pre-iOS 10.0 solution

In this case it'd be better to use the scheduledTimer function that takes a block, as this will allow you to pass arguments to your function:

Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { (timer) in
    SystemClass().setXYZ(xyz: 1.0)
}

For pre-iOS 10.0:

You can also pass userInfo in, including this default value, and then access that info from your inside your selector, like this:

Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(SystemClass().setXYZ(_:)), userInfo: 1.0, repeats: true)

To do this you'd also have to modify your setXYZ function signature to look like this:

@objc func setXYZ(_ sender: Timer) {
    if let xyz = sender.userInfo as? Float {
        print(xyz)
        // do something
    }
}
creeperspeak
  • 5,403
  • 1
  • 17
  • 38