4

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 ?

user1046037
  • 16,755
  • 12
  • 92
  • 138

3 Answers3

9

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})
rintaro
  • 51,423
  • 14
  • 131
  • 139
  • Awesome !! Just a little confused what $0 represents. Wouldn't $0 represent the first argument in the closure ? In this case the closure takes only one argument which is the getter. Could you pls explain – user1046037 Mar 09 '15 at 14:48
  • 1
    `getter` is a closure `Car -> T`. It receives `Car` instance and returns something `T`. In this case, `$0` is a instance of `Car`. – rintaro Mar 09 '15 at 14:52
  • Thanks a ton !!! pretty neat !! Just for my understanding it is the same as `func f1(car: Car, getter: (Car) -> T)` . Just writing `(Car)` within parentheses . You are spot on since `Car` is the only argument, so parentheses is not required – user1046037 Mar 09 '15 at 14:58
  • Yes, with or without parentheses is OK if it accept only one argument. – rintaro Mar 09 '15 at 15:01
4

You can use key value coding:

class Car : NSObject {
    let doors : Int = 4
    let price : Int = 1000
}

Then your f1 function could be:

func f1(car: Car, property: String) {
    println(car.valueForKey(property))
}

And you can call it like so:

f1(car, property: "doors")
f1(car, property: "price")
Rob
  • 415,655
  • 72
  • 787
  • 1,044
1

Solution with key path:

class Car {

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

func f1<T: CustomStringConvertible>(car: Car, property: KeyPath<Car, T>) {

    print(car[keyPath: property])

}

let c1 = Car()

f1(car: c1, property: \.doors)
f1(car: c1, property: \.price)
Bill Chan
  • 3,199
  • 36
  • 32
  • 1
    Nice one, would be even better when you make the function generic type T which conforms to CustomStringConvertible – user1046037 Aug 04 '22 at 13:04