Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 558
Joseph Beuys' Mum Avatar asked Feb 14 '19 09:02

Joseph Beuys' Mum


People also ask

How do I create a computed property in Swift?

Swift Computed Property For example, class Calculator { // define stored property var num1: Int = 0 ... } Here, num1 is a stored property, which stores some value for an instance of Calculator . Here, sum is a computed property that doesn't store a value, rather it computes the addition of two values.

How do you make a generic function in Swift?

Example: Swift Generic Function In the above example, we have created a generic function named displayData() with the type parameter <T> . we have passed a string value, so the placeholder parameter T is automatically replaced by String . the placeholder is replaced by Int .

What are generics How do you make a method or variable generics in Swift?

Generics allow you to declare a variable which, on execution, may be assigned to a set of types defined by us. In Swift, an array can hold data of any type. If we need an array of integers, strings, or floats, we can create one with the Swift standard library.

What is generic protocol in Swift?

Swift enables us to create generic types, protocols, and functions, that aren't tied to any specific concrete type — but can instead be used with any type that meets a given set of requirements.


1 Answers

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
        }
    }
}
like image 102
Dávid Pásztor Avatar answered Oct 28 '22 02:10

Dávid Pásztor