1. Function definition and call
func greet(person: String) -> String {
// 函数名 传入值 传入值类型 返回值类型
let greeting = "Hello" + person
return greeting
}
print( greet(person: "Anna") ) //调用
2. Function parameters and return values
(1) No parameter function
func sayHello() -> String {
return "hello!"
}
print( sayHello() )
(2) Multi-parameter function
func greet(person: String, alreadyGreeted: Bool) -> String {
if alreadyGreeted {
return greetAgain(person: person)
}else {
return greet(personn: person)
}
}
(3) No return value
func greet(person: String) {
print("Hello, \(person)")
}
greet(person: "Dave")
(4) Multiple return values
func minMax(array: [Int]) -> (min: Int, max: Int) {
//业务代码
return (a, b)
}
(5) Optional tuple return type (tuple can be nil)
func minMax(array: [Int]) -> (min: Int, max: Int)? {
//业务代码
return (a, b)
}
(6) Functions that return implicitly
func greeting(for person: String) -> String {
"Hello " + person
}
print(greeting(for: "Dave")
Any function that can be written as a one-line return, return(x) + for.
When calling: method name (for: parameter)
3. Parameter labels and parameter names
(1) Specify the parameter label
func greet(from hometown: String) -> String {
return "from \(hometown)."
}
print( greet(from: "Beijing") )
(2) ignore parameter labels
func some(_ a: Int, b: Int) {
//代码
}
som(1, b: 2)
(3) Default parameter values
func some(a: Int, b: Int = 12) {
//代码
}
some(a: 3, b: 6) //b用6
some(a: 3) //b用12
(4) variable parameters
A variadic parameter can accept zero or more values.
func arith(_ numbers: Double ...) -> {
//代码
}
arith(1, 2, 3, 4, 5)
(5) Input and output parameters (&)
Function parameters are constants by default and cannot be modified. If you want to modify, you must set the parameters as input and output parameters.
func swap(_a: inout Int, _b: inout Int) {
//代码
}
swap(&5, &7)
4. Function type
//类型: (Int, Int) -> Int
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
//类型: () -> Void
func printHello() {
print("H")
}
(1) Use function type
var 变量: (Int, Int) -> Int = add
变量(2, 3) //调用
(2) Function type as parameter type
func printMath(_ mathFunction: (Int, Int) -> Int, a: Int, b: Int) {
print( mathFunction(a, b) )
}
printMath(add, 3, 5)
(3) Function type as return type
func choose(back: Bool) -> (Int) -> Int{
return add
}
let move = choose(back: true)
5. Nested functions
Define functions into other function bodies, which are invisible to the outside world, but can be called by their peripheral functions.
func addMul(a: Int, b: Int, c: Int) -> Int {
func add(d: Int, e: Int) -> Int { return d + e }
func mul(f: Int, g: Int) -> Int { return f * g }
return mul(a, add(b, c))
}
print(addMul(1, 2, 3))