Passing property type as parameter

旧巷老猫 提交于 2019-12-05 14:39:27

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})

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")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!