Swift简单的Closure例子(Simple Closure Examples in Swift)

/////////// Functions as first-class citizens /////////////////

/// Example 1: function as parameter

// Input: a and b as 2 integers to be added up

// Output: returns the sum

func foo(_a:Int,_b:Int) ->Int{

    returna+b

}

func boo(function: (Int,Int) ->Int,_a:Int,_b:Int) ->Int{

    returnfunction(a, b)

}

boo(function:foo,3,4)

/// Example 2: function as return type

func stepBackwards(_location:Int) ->Int{

    return location-1

}

func stepForwards(_location:Int) ->Int{

    return location+1

}

func chooseDirection(_enegyLevel:Int) -> (Int) ->Int{

    if enegyLevel>10{

        return stepBackwards

    }

    return stepForwards

}

func chooseDirectionAsClosure(_enegyLevel:Int) -> (Int) ->Int{

    if enegyLevel>10{

        return{ locationinreturnlocation-1}

    }

    return{ locationinreturnlocation+1}

}

var energyLevel = 12

let moveNearToTen: (Int) -> Int = chooseDirection(energyLevel)

var currentEnergy: Int { return moveNearToTen(energyLevel) }

while energyLevel > 10 {

    energyLevel = currentEnergy

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。