1.函数的返回值
(1) 返回单个返回值
func add(num1:Int,num2:Int) -> Int{
return num1 + num2
}
let result1 = add(1,num2:2)
print(result1) //3
(2) 通过tuple返回多个返回值
func getPoint(x:Int,y:Int) -> (Int,Int){
return (x,y)
}
print(getPoint(1, y: 2)) //"(1, 2)\n"
(3) 返回optional类型的返回值
func getNumFromStr(str:String) -> Int?{
return Int(str)
}
var resultNum = getNumFromStr("123")
resultNum.dynamicType //Optional<Int>.Type
2.函数类型的变量
(1) 函数的类型是由参数信息和返回值信息组成
func add(num1:Int,num2:Int) -> Int{
return num1 + num2
}
//add的类型为(Int,Int) -> Int
(2) 声明一个函数类型的变量
let func1 : (Int,Int) -> Int = add
3.函数类型的参数
func compare(param1:Int,param2:Int,compareFunc:(Int,Int) -> Bool) ->Bool{
return compareFunc(param1,param2)
}
var compareResult = compare(1, param2: 2) { (p1, p2) -> Bool in
return p1>p2
}
print(compareResult)
4.函数类型的返回值
func add(num1:Int,num2:Int) -> Int{
return num1 + num2
}
func multi(num1:Int,num2:Int) -> Int{
return num1 * num2
}
func whichOne(bool:Bool) -> (Int,Int) ->Int{
return bool ? add : multi
}
print(whichOne(true)(1,2)) //打印3
print(whichOne(false)(1,2)) //打印2
5.typealias,为一个函数类型起别名
func add(num1:Int,num2:Int) -> Int{
return num1 + num2
}
func multi(num1:Int,num2:Int) -> Int{
return num1 * num2
}
typealias op = (Int,Int) -> Int
func whichOne(bool:Bool) -> op{
return bool ? add : multi
}
print(whichOne(true)(1,2)) //打印3
print(whichOne(false)(1,2)) //打印2
6.内嵌函数
typealias op = (Int,Int) -> Int
func whichOne(bool:Bool) -> op{
func add(num1:Int,num2:Int) -> Int{
return num1 + num2
}
func multi(num1:Int,num2:Int) -> Int{
return num1 * num2
}
return bool ? add : multi
}
网友评论