Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing property type as parameter

Tags:

closures

swift

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 ?

like image 560
user1046037 Avatar asked Dec 20 '22 06:12

user1046037


1 Answers

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})
like image 105
rintaro Avatar answered Jan 12 '23 06:01

rintaro