function definition
func 函数名(形参列表) -> 返回值类型 {
// 函数体...
}
The format of the formal parameter list:
formal parameter name 1: formal parameter type 1, formal parameter name 2: formal parameter type 2, …
func num() -> Double {
return 3.1415926
}
num()
func sum(v1: Int, v2: Int) -> Int {
return v1 + v2
}
sum(v1: 20, v2: 30)
- The formal parameter defaults to let and can only be let
If a function has no return value, there are three ways to write it.
If a function has no formal parameters, the parentheses after the function name cannot be omitted.
func 函数名(形参列表) -> Void {
// 函数体...
}
func 函数名(形参列表) -> () {
// 函数体...
}
func 函数名(形参列表) {
// 函数体...
}
//无返回值写法
func sayGo() -> Void {
print("Go")
}
sayGo()
func saySiri() -> (){
print("Siri")
}
saySiri()
func sayBye() {
print("Bye")
}
sayBye()
implicit return
- If the entire function body is a single expression, the function will implicitly return this expression
func sum(v1: Int, v2: Int) -> Int {
v1 + v2
}
sum(v1: 30, v2: 40)
Return tuple: implement multiple return values
//返回这组数的和、差、平均值
func calculate (v1: Int, v2: Int) -> (sum : Int, dif: Int, ave: Int){
let sum = v1 + v2
return (sum, v1 - v2, sum >> 1)
}
let result = calculate(v1: 30, v2: 20)
result.sum // 50
result.dif // 10
result.ave // 25
Documentation comments for functions
- Shortcut key option + command + /
/// 求和【概述】
///
///将2个整数相加【更详细的描述】
///
/// - Parameters:
/// - v1: 第一个整数
/// - v2: 第二个整数
/// - Returns: 2个整数的和
///
/// - Note: 传入2个整数即可【批注】
///
func sum(v1: Int, v2: Int) -> Int {
v1 + v2
}
sum(v1: 30, v2: 40)
- Refer to official documentation
Argument Label
- Parameter labels can be modified
func function name (external parameter name local parameter name: formal parameter type)
func goToWork(at time: String) {
print("this time is \(time)")
}
goToWork(at: "10:00")
//this time is 10:00
- Underscores can be used to omit parameter labels
func sum(_ v1: Int, _ v2: Int) -> Int {
v1 + v2
}
sum(30, 40)
Default Parameter Value
func function name (formal parameter name: formal parameter type = default value)
- Parameters can have default values
func check(name: String = "nobody", age: Int, job: String = "none"){
print("name=\(name), age=\(age), job=\(job)")
}
check(name: "Jack", age: 20, job: "Doctor") // name=Jack, age=20, job=Doctor
check(name: "Rose", age: 18) //name=Rose, age=18, job=none
check(age: 10, job: "Batman") //name=nobody, age=10, job=Batman
check(age: 15)//name=nobody, age=15, job=none
- C++'s default parameter values have a restriction: they must be set from right to left. Since Swift has parameter labels, there is no such restriction
- When omitting parameter labels, special attention is required to avoid errors.
// 这里的middle 不可以省略参数标签
func test(_ first: Int = 10, middle: Int, _ last: Int = 30){
}
Variadic Parameter
- A variadic parameter can accept one or more values
- When calling a function, you can use variable parameters to pass in an uncertain number of input parameters.
- Variable parameters are defined by adding ... after the variable type name
- The value passed in as a variable parameter is treated as an array of this type in the function body. For example, an Int... type variable parameter called numbers can be treated as an Int[] type array constant called numbers in the function body.
func sum(_ numbers: Int...) -> Int {
var total = 0
for number in numbers{
total += number
}
return total
}
sum(10, 20, 30, 40) // 100
- a function
最多只能有1个
variadic parameter - The parameter label immediately following the variable parameter cannot be omitted
//参数string不能省略参数标签
func test1(_ numbers: Int..., string: String, _ other: String){
}
test1(10, 20, 30, string: "Jack", "Rose")
Swift’s own print function
print(1, 2, 3, 4, 5) // 1 2 3 4 5
print(1, 2, 3, 4, 5, separator: "_") // 1_2_3_4_5
print("My name is Jake.", terminator: "")
print("My age is 18.")
// My name is Jake.My age is 18.
In-Out Parameter
- You can use inout to define an input and output parameter: the value of the external parameter can be modified inside the function
var number = 20
func test (_ num: inout Int){
num = 30
}
test(&number)
print(number) // 30
//交换两个值
func swapValues(_ v1: inout Int, _ v2: inout Int){
let tmp = v1
v1 = v2
v2 = tmp
}
var num1 = 20
var num2 = 30
swapValues(&num1, &num2)
print(num1, num2)
//可以用元组实现交换两个值
func swapValues(_ v1: inout Int, _ v2: inout Int){
(v1, v2) = (v2, v1)
}
var num1 = 20
var num2 = 30
swapValues(&num1, &num2)
print(num1, num2)
- Variable parameters cannot be marked as inout
- inout parameters cannot have default values
- The inout parameter can only be passed in and can be assigned multiple times.
- The essence of inout parameters is address passing (passing by reference)
Function Overload
- rule
-
- Function names are the same
-
- The number of parameters is different || The parameter types are different || The parameter labels are different
func sum(v1: Int, v2: Int) -> Int {
v1 + v2
}
func sum(v1: Int, v2: Int, v3: Int) -> Int {
v1 + v2 + v3
}// 参数个数不同
func sum(v1: Int, v2: Double) -> Double {
Double(v1) + v2
}// 参数类型不同
func sum(v1: Double, v2: Int) -> Double {
v1 + Double(v2)
}// 参数类型不同
func sum(_ v1: Int, _ v2: Int) -> Int {
v1 + v2
}// 参数标签不同
func sum(x v1: Int, y v2: Int) -> Int {
v1 + v2
}// 参数标签不同
func sum(a: Int, b: Int) -> Int {
a + b
}// 参数标签不同
sum(v1: 10, v2: 20) // 30
sum(v1: 10, v2: 20, v3: 30) // 60
sum(v1: 10, v2: 20.0) // 30.0
sum(v1: 10.0, v2: 20) // 30.0
sum(10, 20) // 30
sum(x: 10, y: 20) // 30
sum(a: 10, b: 20) // 30
Notes on function overloading
- Return value type has nothing to do with function overloading
- When default parameter values and function overloading are used together to create ambiguity, the compiler will not report an error (it will report an error in C++)
func sum(v1: Int, v2: Int) -> Int {
v1 + v2
}
func sum(v1: Int, v2: Int, v3: Int = 10) -> Int{
v1 + v2 + v3
}
// 会调用 sum(v1: Int, v2: Int)
sum(v1: 10, v2: 20)
- When variable parameters, omitted parameter labels, and function overloading are used together to create ambiguity, the compiler may report an error.
func sum(v1: Int, v2: Int) -> Int {
v1 + v2
}
func sum(_ v1: Int, _ v2: Int) -> Int {
v1 + v2
}
func sum(_ numbers: Int...) -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}
// error: Ambiguous use of 'sum'
sum(10, 20)
Inline Function
- If compiler optimization is turned on (Release mode will turn on optimization by default), the compiler will automatically turn some functions into inline functions
-
- Expand function calls into function bodies
- Expand function calls into function bodies
- Which functions will not be automatically inlined?
-
- The function body is relatively long
-
- Contains recursive calls
-
- Including dynamic distribution, etc.
@inline
//永远不会被内联(即使开启了编译器优化)
@inline(never) func test(){
print("test")
}
// 开启编译器优化后,即使代码很长,也会被内联(递归调用函数、动态派发的函数除外)
@inline(__always) func test() {
print("test")
}
- In Release mode, the compiler has enabled optimization and will automatically determine which functions need to be inlined, so there is no need to use @inline
Function Type
- A function type is a data type
- Every function has a type, and the function type
形式参数类型
consists返回值类型
of - Three steps: 1. Define the function; 2. Declare function type variables or constants; 3. Assign values to function type variables (steps 2 and 3 can be combined)
func test(){
}// () -> Void 或者 () -> ()
func sum(a: Int, b: Int) -> Int {
a + b
}// (Int, Int) -> Int
//定义变量
var fn: (Int, Int) -> Int = sum
fn(2,3) // 5 调用时不需要参数标签
function type as function parameter
func sum(v1: Int, v2: Int) -> Int {
v1 + v2
}
func difference(v1: Int, v2: Int) -> Int {
v1 - v2
}
func printResult(_ mathFn: (Int, Int) -> Int, _ a: Int, _ b: Int) {
print("Result:\(mathFn(a, b))")
}
printResult(sum, 5, 2) //Result: 7
printResult(difference, 5, 2) //Result: 3
function type as function return value
func next(_ input: Int) -> Int {
input + 1
}
func previous(_ input: Int) -> Int {
input - 1
}
func forward(_ forward: Bool) -> (Int) -> Int {
forward ? next : previous
}
var fn: (Int) -> Int = forward(true)
fn(3)
forward(false)(3)
- The return value is a function of function type, called
高阶函数
(Higher-Order Function)
typealias
- typealias is used to alias types
typealias Byet = Int8
typealias Short = Int16
typealias Long = Int64
var num1: Byet = 0
var num2: Short = 0
var num3: Long = 0
typealias Date = (year: Int, month: Int, day: Int)
func test(_ date: Date) {
print(date.0)
print(date.year)
}
test((2022, 10, 13))
//2022
//2022
typealias IntFn = (Int, Int) -> Int
func difference(v1: Int, v2: Int) -> Int {
v1 - v2
}
let fn: IntFn = difference
fn(30, 10) // 20
func setFn(_ fn: IntFn){
}
setFn(difference)
func getFn() -> IntFn {
difference
}
- According to the definition of the Swift standard library,
Void
it is the empty tuple()
Nested Function
- Define the function inside the function
func forward(_ forward: Bool) -> (Int) -> Int {
func next(_ input: Int) -> Int {
input + 1
}
func previous(_ input: Int) -> Int {
input - 1
}
return forward ? next : previous
}
forward(true)(3) // 4
forward(false)(3) //2