gpt4 book ai didi

Swift struct 相当于 C++ 可变关键字?

转载 作者:行者123 更新时间:2023-11-30 13:38:20 25 4
gpt4 key购买 nike

Swift 中是否有 C++ mutable 关键字的等效项?我有一个实现包含非变异函数的协议(protocol)的结构,但是内部实现确实会改变内部状态。有没有办法让类的成员变量通过这个函数可变,而不改变协议(protocol)定义,使函数变异

例如

public protocol P {
// f is semantically unmutating
func f
}

public struct S : P {
// f is semantically unmutating, but does change some internal state
public func f {
v += 1
}
private var v: Int // How to mark this as mutable for internal purposes?
...
}

最佳答案

与 C++ 中的相同

public struct S : P {
// f is semantically unmutating, but does change some internal state
public func f {
increment()
}
private mutating func increment() {
v += 1
}
private var v: Int // How to mark this as mutable for internal purposes?
...
}

关于Swift struct 相当于 C++ 可变关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35845526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com