【问题标题】:Unable to append string to mutable array in Swift无法将字符串附加到 Swift 中的可变数组
【发布时间】:2019-01-02 18:15:09
【问题描述】:

上下文 - 我目前正在学习 Swift Struct。所以我决定在 Playground 中创建自己的电话结构。 (见下文)

问题 - phone 结构上的 downloadApp 方法抛出以下错误.. Cannot use mutating member on immutable value: 'self' is immutable

预期结果 - 和平地将新字符串附加到我的 apps 属性,这是一个字符串数组。

Swift 代码

struct Phone {
    let capacity : Int
    let Brand : Sting
    var name: String
    let model: String
    var apps: [String]
    var contacts: [String]

    var formatCapacity: String {
        return "\(capacity)GB"
    }

    func downloadApp(name: String){
        apps.append(name) // ERROR 
    }
}

【问题讨论】:

    标签: arrays swift struct append


    【解决方案1】:

    您只需将downloadApp 标记为mutating。该问题是由于 downloadApp 是在 struct 类型中声明的,这是一种值类型,因此如果您更改结构的任何属性(即此处的 apps 数组),您实际上会更改结构本身。通过将函数标记为mutating,编译器允许通过该类型的成员函数对结构进行此类修改。

    mutating func downloadApp(name: String){
        apps.append(name)
    }
    

    【讨论】:

    • 非常感谢! Apples Intro to app development book 没有告诉我!我猜是婴儿步
    猜你喜欢
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 2014-11-19
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多