传递属性类型作为参数 [英] Passing property type as parameter

查看:95
本文介绍了传递属性类型作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种方法可以将属性传递给函数作为参数?

  class Car {

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

有没有办法将Car属性作为类型传递给函数?



我想实现以下目的:

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

println(car.property)

}

let c1 = Car()

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



关闭帮助,如果是这样?

解决方案

我不确定这是你想要的,但使用闭包:

  func f1< T>(car:Car,getter:Car→T){
println(getter(car))
}

let c1 = Car()

f1(c1,{$ 0.doors})
f1(c1,{$ 0.price})


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 ?

解决方案

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

这篇关于传递属性类型作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆