swift基础语法(四) 函数、闭包(Closures)

//函数基本定义

func 函数名(参数名:参数类型=默认值)  ->返回值类型{代码块}

//无参无返回值函数

func hsmin(){

}

//单参无返回值函数

func prin(st:String){

    println(st)

}

prin("111")

//111

func yuanzu(tup:(String,Int)){

    print("Int:\(tup.1)  String:\(tup.0)")

}

yuanzu(("冯小刚",1))

//Int:1  String:冯小刚



//多参无返回值函数

func addp(a:Int,b:Int){

    println(\(a+b))

}

addp(1,2)

//3



//单参返回值函数

func prt(l:Int)->Int{

    return l+1

}

println("\(prt(2)")

//3

//多参返回值函数

func add(a: Int , b : Int) -> Int

{

    return a+b

}

func del(a : Int, b : Int) -> Int{

    return a-b

}

println(add(3,4))

//7

//参数默认值

func sum( a : Int, b : Int = 1) -> Int{

    return a+b

}

println(sum(3))

//4

//输出参数

func swapTwoInts(inout a: Int, inout b: Int) {

    let temporaryA = a

    a = b

    b = temporaryA

}

var someInt = 3

var anotherInt = 107

swapTwoInts(&someInt, &anotherInt)

println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")



//函数嵌套(匿名函数)

func chooseStepFunction(backwards: Bool) -> (Int) -> Int {

    func stepForward(input: Int) -> Int { return input + 1 }

    func stepBackward(input: Int) -> Int { return input - 1 }

    return backwards ? stepBackward : stepForward

}

var currentValue = -4

let moveNearerToZero = chooseStepFunction(currentValue > 0)

// moveNearerToZero now refers to the nested stepForward() function

while currentValue != 0 {

    println("\(currentValue)... ")

    currentValue = moveNearerToZero(currentValue)

}

println("zero!")

// -4...

// -3...

// -2...

// -1...

// zero!

   个人感觉闭包(Closures)相当于c里面的block只不过在block的基础上重新改良了一下而已

// 闭包的完整写法

{ ( 参数列表 ) -> 返回类型 in 代码块 }

//eg

var a : Array = [3,1,4,2,5,7,6]

var b = sort( a, { (i1 : Int, i2 : Int) -> Bool in retern i1>i2 })

//b=[1,2,3,4,5,6,7]



//swift支持类型识别故简写为

var b = sort( a, {i1, i2 in retern i1>i2})

//b=[1,2,3,4,5,6,7]



//还可以使用参数识别$0,$1

var b = sort( a,{ $0 > $1})

//b=[1,2,3,4,5,6,7]



//无参无返回值闭包

func someFunctionThatTakesAClosure(closure: () -> ()) {

    代码块

}

 

someFunctionThatTakesAClosure({

    代码块

    })

 

someFunctionThatTakesAClosure() {

    代码块

}

 

你可能感兴趣的:(closure)