- parameter和argument的区别
Note: Take care not to confuse the terms “parameter” and “argument”. A function declares its parameters in its parameter list. When you call a function, you provide values as arguments for the functions parameters.
parameter是函数的形参,argument是函数调用时的实参。
- 函数格式
函数的定义要像读一条句子,例如下面:
Print multiple of multiplier 4 and value 2
func printMultipleOf(multiplier: Int, andValue: Int) {
print("\(multiplier) * \(andValue) = \(multiplier * andValue)")
}
printMultipleOf(multiplier: 4, andValue: 2)
- 进一步优化
Print multiple of multiplier 4 and 2
func printMultipleOf(multiplier: Int, and value: Int) {
print("\(multiplier) * \(value) = \(multiplier * value)")
}
printMultipleOf(multiplier: 4, and: 2)
- 如果你不想要函数在调用时显示参数的名字(下划线)
func printMultipleOf(_ multiplier: Int, and value: Int) {
print("\(multiplier) * \(value) = \(multiplier * value)")
}
printMultipleOf(4, and: 2)
func printMultipleOf(_ multiplier: Int, _ value: Int) {
print("\(multiplier) * \(value) = \(multiplier * value)")
}
printMultipleOf(4, 2)
- 给形参添加默认值
func printMultipleOf(_ multiplier: Int, _ value: Int = 1) {
print("\(multiplier) * \(value) = \(multiplier * value)")
}
printMultipleOf(4)
- 函数的返回值(箭头)
func multiply(_ number: Int, by multiplier: Int) -> Int {
return number * multiplier
}
let result = multiply(4, by: 2)
func multiplyAndDivide(_ number: Int, by factor: Int)
-> (product: Int, quotient: Int) {
return (number * factor, number / factor)
}
let results = multiplyAndDivide(4, by: 2)
let product = results.product
let quotient = results.quotient
- 传值和传址
默认swift的形参是let类型的常量,所以我们不能作如下操作。
func incrementAndPrint(_ value: Int) {
value += 1
print(value)
}
报错
Left side of mutating operator isn't mutable: 'value' is a 'let' constant
- inout(copy-in copy-out)
func incrementAndPrint(_ value: inout Int) {
value += 1
print(value)
}
inout表明要传址了,我们要在调用的时候做点小修改(取地址符是时候出场了)
var value = 5
incrementAndPrint(&value)
print(value)
- 函数作为参数
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
func printResult(_ function: (Int, Int) -> Int, _ a: Int, _ b: Int) {
let result = function(a, b)
print(result)
}
printResult(add, 4, 2)
- 函数从没返回值(Never关键字)
func noReturn() -> Never {
while true {
}
}
- stride函数介绍
for index in stride(from: 10, to: 22, by: 4) {
print(index)
}
// prints 10, 14, 18
for index in stride(from: 10, through: 22, by: 4) {
print(index)
}
// prints 10, 14, 18, and 22
网友评论