Blog

Swift 关键字--mutating

引出问题

使用 class 来定义一个计数器

class Counter {
    var count: Int    
    init(count: Int = 0) {
        self.count = count
    }
    //计数加1的方法
    func increment() {
        count += 1
    }
}

代码很简单,那改成 struct 呢?

struct Counter {
    var count: Int    
    init(count: Int = 0) {
        self.count = count
    }
    
    // ❌error:Left side of mutating operator isn't mutable: 'self' is immutable
    func increment() {
        count += 1
    }
}

直接报错,因为在Swift中,struct和enum是值类型(value type),class是引用类型(reference type)。对于值类型,默认情况下实例方法中是不可以修改其属性的

解决办法

此时swift关键字mutating就可以发挥作用了,代码如下

struct Counter {
    var count: Int    
    init(count: Int = 0) {
        self.count = count
    }
    
    // 使用 mutating 关键字,ok
    mutating func increment() {
        count += 1
    }
}

应用案例

除此之外,还可以列举一些常用场景比如:

给 Array 扩展一个 remove(_:) 方法,此时就需要用 mutating

extension Array where Element: Equatable {
    
    // Remove first collection element that is equal to the given `object`:
    mutating func remove(_ object: Element) {
        if let index = firstIndex(of: object) {
            remove(at: index)
        }
    }
}
Tagged with:
👈 使用 Hugo + Travis CI + Github Pages 搭建静态博客使用 gitlab 搭建代码托管平台 👉