是否可以在 Swift 中创建具有 Self 或关联类型要求的通用计算属性,如果可以,如何创建?

Jos*_*Mum 5 generics swift computed-properties

考虑以下:

protocol SomeProtocol: Equatable {}

// then, elsewhere...

var someValue: Any?

func setSomething<T>(_ value: T) where T: SomeProtocol {
    someValue = value
}

func getSomething<T>() -> T? where T: SomeProtocol {
    return someValue as? T
}
Run Code Online (Sandbox Code Playgroud)

这些函数工作正常,但本质上就像计算属性一样。有什么方法可以实现以下内容吗?

var something<T>: T where T: SomeProtocol {
    get { return someValue as? T }
    set { someValue = newValue }
}
Run Code Online (Sandbox Code Playgroud)

感谢您的阅读。如果这个问题已经在其他地方被问过,我很抱歉,我已经搜索过,但有时我的搜索功能很弱。

Dáv*_*tor 6

您需要在泛型类型上定义计算属性,计算属性本身不能定义泛型类型参数。

struct Some<T:SomeProtocol> {
    var someValue:Any

    var something:T? {
        get {
            return someValue as? T
        }
        set {
            someValue = newValue
        }
    }
}
Run Code Online (Sandbox Code Playgroud)