Define and call functions
Define the function as follows:
func greet(person: String) -> String {
let greeting = "Hello, " + person + "!"
return greeting
}
Copy the code
Call a function
greet(person: "DDD")
Copy the code
- You can use tuples to return multiple values
- You can also return values using optional types
Formal parameters
- Each function-form parameter contains a parameter label and a parameter name.
- Parameter tags are used when calling a function
- Parameter names are used in the implementation of the function
- By default, the parameter name is used as the parameter label
- You can use
_
Omit function labels
- Variable form parameter
- You can accept multiple or zero special types.
- Insert three dots after the type name of the formal parameter
.
To write formal parameters - The values passed to the mutable arguments are treated as arrays of the corresponding types in the function body
func arthmeticMean(_ numbers: Double...). -> Double {
val total: Double = 0
for number in numbers {
total + = number
}
return total / Double(numbers.count)
}
arthmeticMean(1.2.3.4.5)
Copy the code
- Add one at the beginning of the formal parameter definition
inout
Keywords can define an input/output form parameter.
func swap(_ a: inout Int._ b: inout Int){
let tm = a
a = b
b = tm
}
var some = 3
var another = 108
swap(&some.&another) // some = 108; another = 3
Copy the code
- Each function has a specific function type, which consists of a formal argument type and a return type
func printMathResult(_ mathFunction: (Int.Int) - >Int._ a: Int._ b: Int ) {
print(\(mathFuntion(a, b)))
}
Copy the code
closure
- A closure expression is a syntax for writing a closure in a short line
{(parameters) -> (return type) in
statements
}
//example
let names = [.]
var reversedNames = names.sorted(by: { (s1: String, s2: String) - >Bool in
return s1 > s2
})
Copy the code
- Infer types from context
- The sort closure is passed to the function as an actual argument, so Swift can infer its formal argument and return type
var reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )
Copy the code
- Implicitly returned from a single-expression closure
- Single-expression closures can implicitly return the result of their delayed expression by removing the return keyword from their declaration
var reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )
Copy the code
- Shorthand for the actual parameter name
var reversedNames = names.sorted(by: { $0 > The $1})Copy the code
- Following the closure
- If you need to pass a long closure expression as the last actual argument to a function, using trailing closures will increase the readability of the function.
- A trailing closure is a closure expression that is written outside the parentheses of a function form parameter
var reversedNames = names.sorted{ $0 > The $1 }
Copy the code