//函数基本定义
func 函数名(参数名:参数类型=默认值) ->返回值类型{代码块}
//无参无返回值函数
func hsmin(){
}
//单参无返回值函数
func prin(st:String){
println(st)
}
prin("")
//
func yuanzu(tup:(String,Int)){
print("Int:\(tup.1) String:\(tup.0)")
}
yuanzu(("冯小刚",))
//Int:1 String:冯小刚 //多参无返回值函数
func addp(a:Int,b:Int){
println(\(a+b))
}
addp(,)
//3 //单参返回值函数
func prt(l:Int)->Int{
return l+
}
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(,))
//7
//参数默认值
func sum( a : Int, b : Int = ) -> Int{
return a+b
}
println(sum())
//4
//输出参数
func swapTwoInts(inout a: Int, inout b: Int) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt =
var anotherInt =
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 + }
func stepBackward(input: Int) -> Int { return input - }
return backwards ? stepBackward : stepForward
}
var currentValue = -
let moveNearerToZero = chooseStepFunction(currentValue > )
// moveNearerToZero now refers to the nested stepForward() function
while currentValue != {
println("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
println("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!
个人感觉闭包(Closures)相当于c里面的block只不过在block的基础上重新改良了一下而已
// 闭包的完整写法
{ ( 参数列表 ) -> 返回类型 in 代码块 }
//eg
var a : Array = [,,,,,,]
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,{ $ > $})
//b=[1,2,3,4,5,6,7] //无参无返回值闭包
func someFunctionThatTakesAClosure(closure: () -> ()) {
代码块
} someFunctionThatTakesAClosure({
代码块
}) someFunctionThatTakesAClosure() {
代码块
}