Search code examples
swiftgenericscomputed-properties

Is is possible to create generic computed properties with Self or associated type requirements in Swift, and if so how?


Consider the following:

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
}

These functions work fine but essentially act like computed properties. Is there any way to implement something like the following?

var something<T>: T where T: SomeProtocol {
    get { return someValue as? T }
    set { someValue = newValue }
}

Thank you for reading. Apologies if this question has already been asked elsewhere, I have searched but sometimes my search fu is weak.


Solution

  • You need to define the computed property on a generic type, the computed property itself cannot define a generic type parameter.

    struct Some<T:SomeProtocol> {
        var someValue:Any
    
        var something:T? {
            get {
                return someValue as? T
            }
            set {
                someValue = newValue
            }
        }
    }