函数定义:用来完成特定任务的代码块
常用表现形式:
1 无参数无返回值
func study() -> Void { }
func study() -> () { }
func study() { }
2 有参数无返回值
func study(v: Int) { print(v) }
3 无参数有返回值
func study() ->String{
return "hello"
}
4 有参数有返回值(如果{}中只有1行,可省略return)
func study(v1:Int,v2:Int) -> Int{
return v1 + v2
}
study(v1:10, v2:20)
一、实现多返回值:返回元祖
func study(v1: Int, v2: Int) -> (sum: Int, reduce: Int){
return (v1+v2, v1-v2)
}
let result= study(v1:10, v2:5)
result.sum // 15
result.reduce // 5
二、参数标签
func loveStudy(he time: String) {
print("this time is\(time)")
}
loveStudy(he: "09:00") // this time is 09:00
2.1 可以用下划线_省略参数标签
func sum(_ v1: Int,_ v2: Int) -> Int{
v1 + v2
}
sum(10,20) // 30
2.2 默认参数值,有默认值的参数可选传,没有默认值的参数为必传
func checkUser(name: String="hello",age: Int=18) {
print("name is \(name), age is \(age)")
}
checkUser(name: "world", age: 19) //name is world, age is 19
checkUser(name: "ios") //name is ios, age is 18
checkUser(age: 20) //name is hello, age is 20
2.3 可变参数:1个函数最多只能有1个可变参数
func sum2(_ numbers: Int...) -> Int{
var total =0
for numer in numbers {
total += numer
}
return total
}
sum2(1,2,3,4,5) // 15
2.4 紧跟在可变参数后面的参数,不能省略参数标签
func test(_ numbers: Int..., v: Int) { }
三、swift自带print函数
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
public func print(_ items: Any..., separator: String = " ", terminator: String = "\n")
print(1,2,3) //1 2 3\n
print(1,2,3, separator: "_", terminator: "和") //1_2_3和
四、inout:输入输出参数,可以在函数内部修改外部实参的值
4.1 inout不能有默认值
4.2 可变参数(类似Int...)不能标记为inout
4.3 inout参数本质是地址传递的
func changeValues(_ v1: inout Int, _ v2: inout Int) {
v1 = 30
v2 = 40
}
var num1 = 10
var num2 = 20
changeValues(&num1, &num2)
num1 // 30
num2 // 40