标签:
//: Playground - noun: a place where people can play import UIKit func add(a:Int, b:Int) -> Int { return a + b } // 其中, (Int, Int) -> Int 就是显式的声明函数类型 let anotherAdd:(Int, Int) -> Int = add anotherAdd(3, 4) /*--------------------------------------------------------------------*/ func sayHello(nickName:String) { print("Hello, \(nickName)") } // 这里需要注意的是无返回值的函数类型的声明格式 let anotherGreeting:(String) -> Void = sayHello anotherGreeting("Rinpe Chan") // 或者写成 let greeting:(String) -> () = sayHello greeting("BoBo") // 或者写成(只有一个参数的时候有效) let anotherHello:String -> () = sayHello anotherHello("my son") /*------------------------------举个栗子--------------------------------*/ // 假设老师要对两组学生的分数进行不同操作 func changeScores1(inout scores:[Int]) { for index in 0..<scores.count { scores[index] += 3 } } func changeScores2(inout scores:[Int]) { for index in 0..<scores.count { scores[index] -= 5; } } var scores1 = [36, 61, 78, 99, 100] changeScores1(&scores1) var scores2 = [12, 45, 76, 88, 96] changeScores2(&scores2) // 其实对于上面两个方法, 只是for循环里面的内容不同, 也就是老师对分数的操作 // 可以简化为: func changeScores(op:(Int) -> Int, inout scores:[Int]) { for index in 0..<scores.count { op(scores[index]) } } func op1(originScore:Int) -> Int { return originScore + 3 } func op2(originScore:Int) -> Int { return originScore - 5 } changeScores(op1, scores: &scores1) changeScores(op2, scores: &scores2)
标签:
原文地址:http://www.cnblogs.com/Rinpe/p/5054309.html