Swift初识-3
func math(num: Int, num1: Int, str: String) -> Int { return num + num1 }
func find(id: Int) -> (name: String, age: Int) {
if id > 0 {
return ("jack", 12)
} else {
return ("None", 0)
}
}
var person = find(12)
print("he is name \(person.name), age is \(person.age)")
func addStudent(name: String, age: Int, id: Int) { }
addStudent("jack", age: 12, id: 1024)
func addStudent(name: String, Stu_age age: Int, Stu_age id: Int) {}
addStudent("Jack", Stu_age: 12, Stu_age: 20)
⚠️一旦定义了外部参数名,在调用函数时就必须加上外部参数名
简写:使用#能简化外部参数名的定义 (新语法修改了,不再适用Swift 3)
func math(name: String, _ age: Int = 12) { } math("jack", 23)
func math(let name: String) // let 可省略
func append(var string: String, suffix: String, count: Int) -> String {
for _ in 0..<count{
string += suffix
}
return string
}
func change(inout num1: Int, inout num2: Int) -> () {
let temp = num1
num1 = num2
num2 = temp
} // 交换外部变量的两个值
var a = 20; var b = 10
change(&a, num2: &b) // 传入的参数前面必须加 &
num1 = num1 + num2 & num1 = num1^num2
num2 = num1 - num2 & num2 = num1^num2
num1 = num1 - num2 & num1 = num1^num2
func plusAndMinus(num1: Int, num2: Int) -> (sum: Int, min: Int) {
return (num1 + num2, num1 - num2)
}
var result = plusAndMinus(22, num2: 14)
result.sum // 36
result.min // 8
func plusAndMinus(num1: Int, num2: Int,inout sum: Int, inout min: Int) -> () {
sum = num1 + num2
min = num1 - num2
}
var sums = 0; var mins = 0
plusAndMinus(12, num2: 6, sum: &sums, min: &mins )
sums // 18
mins // 6