Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

615
Vistas
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.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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
        }
    }
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda