美文网首页
Swift4:func

Swift4:func

作者: Roct | 来源:发表于2017-11-22 17:02 被阅读7次

    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

    相关文章

      网友评论

          本文标题:Swift4:func

          本文链接:https://www.haomeiwen.com/subject/sdfovxtx.html