Ho una classe semplice che il metodo init
accetta una funzione Int e una funzione di callback.Come passare le funzioni di callback in Swift
class Timer {
var timer = NSTimer()
var handler: (Int) -> Void
init(duration: Int, handler: (Int) -> Void) {
self.duration = duration
self.handler = handler
self.start()
}
@objc func someMethod() {
self.handler(10)
}
}
Poi nel ViewController ho questo:
var timer = Timer(duration: 5, handler: displayTimeRemaining)
func displayTimeRemaining(counter: Int) -> Void {
println(counter)
}
Questo non funziona, ottengo il seguente:
'Int' is not a subtype of 'SecondViewController'
Edit 1: Aggiunta di codice completo.
Timer.swift
import UIKit
class Timer {
lazy var timer = NSTimer()
var handler: (Int) -> Void
let duration: Int
var elapsedTime: Int = 0
init(duration: Int, handler: (Int) -> Void) {
self.duration = duration
self.handler = handler
self.start()
}
func start() {
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0,
target: self,
selector: Selector("tick"),
userInfo: nil,
repeats: true)
}
func stop() {
timer.invalidate()
}
func tick() {
self.elapsedTime++
self.handler(10)
if self.elapsedTime == self.duration {
self.stop()
}
}
deinit {
self.timer.invalidate()
}
}
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
@IBOutlet var cycleCounter: UILabel!
var number = 0
var timer = Timer(duration: 5, handler: displayTimeRemaining)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnIncrementCycle_Click(sender: UIButton){
cycleCounter.text = String(++number)
println(number)
}
func displayTimeRemaining(counter: Int) -> Void {
println(counter)
}
}
Ho appena iniziato con Swift quindi sono molto verde. Come dovresti passare i callback? Ho esaminato degli esempi e questo dovrebbe funzionare credo. La mia classe è definita in modo errato per il modo in cui sto passando la richiamata?
Grazie
Prova a passare 'self.displayTimeRemaining' . Swift potrebbe aver bisogno di un riferimento esplicito al metodo di istanza per disambiguare le cose; So che è comune in altre lingue.(Purtroppo non ho un Mac a portata di mano, quindi non posso testare se questo lo risolve per te.) – sapi
Non ha funzionato. :(Questo è l'errore ora: ''SecondViewController ->() -> SecondViewController!' Non ha un membro chiamato 'displayTimeRemaining'. Mi chiedo se forse ho dichiarato la funzione in modo errato all'interno del controller? Ho usato la sintassi di base che vedere nel codice sopra. – Fernando
dovrebbe auto.duration e self.start() in init() essere timer.duration e timer.start()? – davecom