gpt4 book ai didi

swift - 如何定义可以在协议(protocol)扩展中设置和获取的变量

转载 作者:可可西里 更新时间:2023-11-01 01:56:42 25 4
gpt4 key购买 nike

我来自 Java 世界。现在我正在使用 Swift 4 编程。

我想在 Swift 中实现抽象类,我知道在 Swift 中没有抽象类的概念。但我知道我们可以通过使用协议(protocol)在 Swift 中模仿这个概念。例如,这是我尝试过的:

// With protocol, I can define functions that concrete class have to implement
protocol ProductProvider {
func getProductNumber() -> Int
}

// with protocol extension, I can define shared (computed) properties and functions among concrete classes that comply with this protocol
extension ProductProvider {
var maxProductCount: Int {
return 10
}
}

但是现在,我想要一个可以设置和获取的共享变量(“共享”意味着与符合此协议(protocol)的类共享):

extension ProductProvider {
var maxProductCount: Int {
set(newValue) {
// set to what if I couldn't define private stored variable in extension to hold the most recent set value ?
}
get{
// how to return the most recent value set?
}
}
}

我的问题在上面代码的注释中。我如何在 Swift 4 中设置和获取协议(protocol)扩展中的变量?如果不可能,有哪些可行的解决方法?

最佳答案

我认为最简单的方法是使用 getter 和 setter 在协议(protocol)中定义变量。然后在您的符合对象中,您应该将变量声明为符合。一个例子:

protocol AbstractObject {

var maxProductCount: Int { get set }
}

struct ConformObject: AbstractObject {

var maxProductCount: Int
}

现在您可以在默认实现中使用您的变量

extension AbstractObject {

mutating func addOne() -> Int {
self.maxProductCount += 1
return self.maxProductCount
}
}

关于swift - 如何定义可以在协议(protocol)扩展中设置和获取的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52643859/

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