当一个参数设置了默认参数的时候,其实是会生成两个函数,一个是有这个参数的函数,一个是没有这个参数的函数;
这个参数并不一定是可选类型的
- 下面详细介绍下函数
import UIKit
无返回值的函数(如果没有参数,直接一个空的括号就可以了)
func imFunction(name:String, age:Int){
print("this is my function, my name is \(name), my age is \(age)")
}
imFunction(name: "zhang", age: 20)
有返回值的函数(如果没有参数,直接一个空的括号就可以了)
func imFunction01(name:String, age:Int)->String{
let result = "My name is "+name + "And my age is "+"\(age)"
return result
}
imFunction01(name: "jack", age: 10)
函数的使用注意:
- 1,默认参数,在定义次参数的时候直接后面赋值,就是默认参数 age:Int = 10
func infoFunc(name:String, age:Int = 10)->String{
return "Name is \(name), age is \(age)"
}
infoFunc(name: "zhangdanfneg")
infoFunc(name: "zhangdanfeng", age: 20)
- 2,可变个数参数,在定义参数的时候直接在后面加上...: num:Int...
func sum(num:Int...)->Int{
var sum = 0
for n in num{
sum += n
}
return sum
}
sum(num: 2, 3,4,5)
//如果不想要展示前面的num:提示,如下:
func sum01(_ num:Int...)->Int{
var sum = 0
for x in num{
sum += x
}
return sum
}
sum01(2,4,5)//和前面的对比:sum(num: 2, 3,4,5) , ********_下划线的作用就是这个,把通用参数变成内部参数********
- 3,指针类型:
var m = 10
var n = 30
m
n
//方法一
func swapNum( m:Int, n:Int){
var m = m
var n = n
let tem = m
m = n
n = tem
}
swap(&m, &n)
m
n
//方法二
func swapNum( m:inout Int, n:inout Int){
let tem = m
m = n
n = tem
}
swap(&m, &n)
m
n