1. 函数参数传递

当函数需要修改传入的参数值时,可以使用 inout 关键字。例如,下面的函数用于交换两个整数的值:

func swapInts(_ a: inout Int, _ b: inout Int) {
    let temp = a
    a = b
    b = temp
}

var x = 3
var y = 5
swapInts(&x, &y)
print("x=(x), y=(y)") // 输出 'x=5, y=3'
  1. 方法参数传递

类的方法也可以使用 inout 关键字来修改实例属性的值。例如:

class Person {
    var age = 0
    
    func increaseAge(by years: inout Int) {
        age += years
        years = 0
    }
}

var person = Person()
var years = 5
person.increaseAge(by: &years)
print("person.age=(person.age), years=(years)") // 输出 'person.age=5, years=0'
  1. 泛型函数参数传递

当使用泛型函数时,有时需要修改传入的参数值。此时,可以使用 inout 关键字。例如:

func removeFirst<T>(_ array: inout [T]) -> T? {
    if array.isEmpty {
        return nil
    }
    let first = array[0]
    array.remove(at: 0)
    return first
}

var arr = [1, 2, 3]
if let first = removeFirst(&arr) {
    print("first=(first), arr=(arr)") // 输出 'first=1, arr=[2, 3]'
}
Swift inout 关键字:应用场景及示例

原文地址: https://www.cveoy.top/t/topic/na5t 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录