Swift3.0Swift5.0iOS Swift5 语法

Swift语法 Swift5 【03 - 函数】

2020-05-08  本文已影响0人  Liwx

iOS Swift 语法 底层原理内存管理分析 专题:【iOS Swift5语法】

00 - 汇编
01 - 基础语法
02 - 流程控制
03 - 函数
04 - 枚举
05 - 可选项
06 - 结构体和类
07 - 闭包
08 - 属性
09 - 方法
10 - 下标
11 - 继承
12 - 初始化器init
13 - 可选项


目录


01-函数的定义

func pi() -> Double {
    return 3.14
}
func sum(v1: Int, v2: Int) -> Int {
//    v1 += 1 // error: left side of mutating operator isn't mutable: 'v1' is a 'let' constant
    return v1 + v2
}
sum(v1: 10, v2: 20)
// Void是空元组别名定义
func sayHello() -> Void {
    print("Hello")
}

// 无返回值实际是返回空元组
func sayHello() -> () {
    print("Hello")
}

// 无返回值可省略返回值, 推荐写法
func sayHello() {
    print("Hello")
}

02-隐式返回(Implicit Return)

func sum(v1: Int, v2: Int) -> Int {
    v1 + v2
}
sum(v1: 10, v2: 20) // 30

03-返回元组 实现多返回值

func calculate(v1: Int, v2: Int) -> (sum: Int, difference: Int, average: Int) {
    let sum = v1 + v2
    let defference = v1 - v2
    let average = sum >> 1
    return (sum, defference, average)
}

let result = calculate(v1: 20, v2: 10)
result.sum // 30
result.difference // 10
result.average  // 15

04-函数的文档注释

/// 求和[概述]
///
/// 将2个整数相加[更加详细的描述]
/// - Parameters:
///   - v1: 第1个整数参数
///   - v2: 第2个整数参数
/// - Returns: 2个整数的和
/// - Note: 传入2个整数即可[批注]
///
func sum(v1: Int, v2: Int) -> Int {
    v1 + v2
}
sum(v1: 10, v2: 20)

05-参数标签(Argument Label)

func goToWork(at time: String) {
    print("this time is \(time)")
}
goToWork(at: "08:00") // this time is 08:00
func sum(_ v1: Int, _ v2: Int) -> Int {
    v1 + v2
}
sum(10, 20) // 30

06-默认参数值(Default Parameter Value)

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

// 这里的middle不可以省略参数标签
func test(_ first: Int = 10, middle: Int, _ last: Int = 30) {}
test(middle: 20)

07-可变参数(Variadic Parameter)

func sum (_ numbers: Int...) -> Int {
    var total = 0
    for num in numbers {
        total += num
    }
    return total
}
sum(10, 20, 30, 40) // 100
func test(_ numbers: Int..., string: String, _ other: String) {}
test(10, 20, 30, string: "Jack", "Rose")

08-Swift自带的print函数

/// - Parameters:
///   - items: Zero or more items to print.
///   - separator: A string to print between each item. The default is a single
///     space (`" "`).
///   - terminator: The string to print after all items have been printed. The
///     default is a newline (`"\n"`).
// public func print(_ items: Any..., separator: String = " ", terminator: String = "\n")

// separator: 分隔符 默认空格
// terminator: 结束符 默认\n

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.

09-输入输出参数(In-Out Parameter)

// 使用inout定义函数参数,调用时需加&符号
func swapValues(_ v1: inout Int, _ v2: inout Int) {
    let tmp = v1
    v1 = v2
    v2 = tmp
}
var num1 = 10
var num2 = 20
swapValues(&num1, &num2)
print(num1, num2)
// 使用元组方式交换数据
func swapValues1(_ v1: inout Int, _ v2: inout Int) {
    (v1, v2) = (v2, v1)
}

var num3 = 10
var num4 = 20
swapValues1(&num3, &num4)
print(num3, num4)

10-函数重载

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(a: Int, b: Int) -> Int {
    a + b
} // 参数标签不同

11-函数重载注意点1

// 返回值Int类型
func sum(v1: Int, v2: Int) -> Int { v1 + v2 }
// 无返回值
func sum(v1: Int, v2: Int) {}
// 以下调用存在歧义,编译器无法辨别调用哪个函数
sum(v1: 10, v2: 20) // error: ambiguous use of 'sum(v1:v2:)'

func sum1(v1: Int, v2: Int) -> Int {
    v1 + v2
}

func sum1(v1: Int, v2: Int, v3: Int = 10) -> Int {
    v1 + v2 + v3
}

// 会调用sum(v1: Int, v2: Int)
sum1(v1: 10, v2: 20)  // 30

12-函数重载注意点2

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(_ v1: Int, _ v2: Int)函数
sum(10, 20)

13-内联函数(Inline Function)

// 永远不会被内联(即使开启了编译器优化)
@inline(never) func test() {
    print("test")
}
// 调用test()函数,编译器直接优化成调用 print("test"), 这样免去为test函数分配栈空间,以达到优化效果
@inline(__always) func test1() {
    print("test1")
}

14-函数类型(Function Type)

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, 调用时不需要参数标签

15-函数类型作为函数参数

func sum(v1: Int, v2: Int) -> Int {
    v1 + v2
}

func difference(v1: Int, v2: Int) -> Int {
    v1 - v2
}

func printResult(_ mathFn: (Int, Int) -> Int, _ v1: Int, _ v2: Int) {
    print("Result: \(mathFn(v1, v2))")
}

printResult(sum, 5, 2) // Result: 7
printResult(difference, 5, 2) // Result: 3

16-函数类型作为函数返回值

unc next(_ input: Int) -> Int {
    input + 1
}

func previous(_ input: Int) -> Int {
    input - 1
}

// 返回值类型为 (Int) -> Int 函数类型
func forward(_ forward: Bool) -> (Int) -> Int {
    forward ? next : previous
}

forward(true)(3)    // 4, 相当于执行next(3)
forward(false)(3)   // 2, 相当于执行previous(3)

17-typealias

typealias Byte = Int8
typealias Short = Int16
typealias Long = Int64

typealias Date = (year: Int, month: Int, day: Int)
func test(_ date: Date) {
    print(date.0)
    print(date.year)
}
test((2020, 1, 1))

typealias IntFn = (Int, Int) -> Int

func difference(v1: Int, v2: Int) -> Int {
    v1 - v2
}

let fn: IntFn = difference
fn(30, 20)  // 10

func setFn(_ fn: IntFn) { }
setFn(difference)

func getFn() -> IntFn { difference }

18-嵌套函数

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

iOS Swift 语法 底层原理内存管理分析 专题:【iOS Swift5语法】

下一篇: 04 - 枚举
上一篇: 02 - 流程控制


上一篇下一篇

猜你喜欢

热点阅读