callback的运用
struct里的运用
class FinishAlertView{
var buttonPressed : ((Int) -> Void)?
func getNextPress(){
buttonPressed?(2)
}
}
struct PressCounter{
var count = 0
mutating func buttonPressed(at Index : Int){
count += Index
}
}
let finish = FinishAlertView()
var counter = PressCounter()
finish.buttonPressed = {counter.buttonPressed(at : $0)}
finish.getNextPress()
finish.getNextPress()
finish.getNextPress()
finish.getNextPress()
finish.getNextPress()
counter.count // 10
callback在class里的运用
class FinishAlertView{
var buttonPressed : ((Int) -> Void)?
func getNextPress(){
buttonPressed?(2)
}
}
class PressCounterClass {
var count = 0
func buttonPressed(at Index : Int){
count += Index
}
}
let finish = FinishAlertView()
var counterClass = PressCounterClass()
finish.buttonPressed = {[weak counterClass] index in // 防止循环引用
counterClass?.buttonPressed(at: index)
}
finish.getNextPress()
finish.getNextPress()
finish.getNextPress()
finish.getNextPress()
finish.getNextPress()
counterClass.count // 10
Closure Expressions和Closure
网友评论