The use of Swift's functions has changed a lot in swift2.
/***param: personName 参数*returns: String为返回值*/func sayHello(personName: String) -> String { return"Hello " + personName;}
/*swift2中函数的调用必须要使用标签或者别名,没有别名第一个标签不带*/func add(a: Int, b: Int) -> Int { return a + b;}print(add(1b:2));
/*如果使用了别名,函数调用的时候必须使用别名*/func add(num1 a: Int, b: Int) -> Int { return a + b;}print(add(num11b:2));
Return multiple values
/ * Returns multiple values, which is the return of a tuple * /varNums = [1,2,3,4,5]func Minmax (Array: [Int]), (Min:int, Max:int) {varMinnum =Array[0];varMaxnum =Array[0]; forNum inArray{ifNum < minnum {minnum = num}Else ifnum > Maxnum {maxnum = num}}return(Minnum, maxnum);}Print(Minmax (nums). Max);Print(Minmax (nums). min);
Returns an optional tuple
varNums = [1,2,3,4,5]func Minmax (Array: [Int]) (Min:int, max:int)? {if Array. isEmpty {returnNil }varMinnum =Array[0];varMaxnum =Array[0]; forNum inArray{ifNum < minnum {minnum = num}Else ifnum > Maxnum {maxnum = num}}return(Minnum, maxnum);}Print(Minmax (nums)!. MAX);Print(Minmax (nums)!. MIN);
Default parameters
numFun(num: Int = 22) { print(num);}numFun();//输出22
Variable parameters
func numAdd(nums: Int...) { varsum=0; in nums { sum+= num; } print(sum);}numAdd(123);
The case of calling functions without tags
func addNum(_ a:Int, _ b: Int) { a + b;}addNum(a, b);
Variable parameters
function parameters are constants by default and cannot be changed inside the function values
To change the value of a parameter inside a function, use a variable as a parameter
func swapNum(varvar b: Int) { var temp = a; a = b; b = temp;}
In-out parameters
The function defaults to using the copy transfer function
Using the In-out modifier parameter to indicate that the parameter is using a pointer transfer function
ab: Int) { let temp = a; a = b; b = temp;}var1;var2b: &b);print("a is \(a), b is \(b)");
function type
func add(a: Int, b: Int) -> Int { return a + b;}print1b:2));/*声明一个变量,后面是函数类型*/varaddNum(Int, Int) -> Int = add;print(addNum(23));
function type as parameter
func result(numFun: (Int, Int) -> Int, a: Int, b: Int) { print(numFun(a, b));}result(addNum, a: 6, b: 7);
function type as return value
/*返回一个函数*/func chooseFunc() ->(Int) -> Int {}
Nested functions
func addNum(a: Int, b: Int) { func printNum() { print(22); } printNum(); print(a + b);}var a = 1;var b = 3;addNum(a, b:b);
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Swift-Summary" function