Search code examples
swiftclosures

Passing property type as parameter


Is there a way to pass the property to a function as a parameter ?

class Car {

    let doors : Int = 4
    let price : Int = 1000
}

Is there a way to pass the Car property as a type to a function ?

I would like to achieve the following:

func f1(car: Car, property: SomeType) {

    println(car.property)

}

let c1 = Car()

f1(c1, doors)
f1(c1, price)

Would closures help, if so how ?


Solution

  • I'm not sure this is what you want, but using closure:

    func f1<T>(car: Car, getter: Car -> T) {
        println(getter(car))
    }
    
    let c1 = Car()
    
    f1(c1, {$0.doors})
    f1(c1, {$0.price})