Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

613
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!