简体   繁体   中英

How to create selector for function with optional parameter in Swift 3?

I need to create a timer like this:

timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(dismissNotification(completion:)), userInfo: nil, repeats: false)

func dismissNotification(completion: (() -> ())? = nil) { ... }

but it crashes without displaying any reason. Why it happens? And how to workaround this?

(NS)Timer allows only two types of actions:

Without a parameter

  • func timerFireMethod()

With a single parameter passing the affected (NS)Timer instance

  • func timerFireMethod(_ timer : Timer)

However in iOS 10 / macOS 10.12 you can use a new API with a closure

class func scheduledTimer(withTimeInterval interval: TimeInterval, 
                                            repeats: Bool, 
                                              block: @escaping (Timer) -> Void) -> Timer

The function crashes because the timer passes itself to the selector method. And the selector method expects an anonymous function.

One thing you can do is this:

timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(dismissNotification(timer:)), userInfo: nil, repeats: false)

func dismissNotification(timer: Timer) {
    //call dismissNotification(completion) here
}
func dismissNotification(completion: (() -> ())? = nil) { ... }

Also, you can pass additional data to the dismissNotification(timer: Timer) function using the Timer.userInfo property.

The completion handler needs to have the signature

 func dismissNotification(completion: Timer) { ... }

It is also possible to omit the Timer parameter:

 func dismissNotification() { ... }

Dispatch also provides similar functionality allowing the code to be executed on an arbitrary queue:

// It's necessary to keep a reference to timer
let timer = DispatchSource.makeTimerSource(queue: DispatchQueue.main)
timer.scheduleRepeating(deadline: DispatchTime.now(), interval: DispatchTime.seconds(2))
timer.setEventHandler() { ... } 
timer.resume()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM