将属性类型作为参数传递

问题描述 投票:0回答:3

有没有办法将属性作为参数传递给函数?

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)

闭包有帮助吗?如果有的话怎么办?

swift closures
3个回答
9
投票

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

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

let c1 = Car()

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

5
投票

正如 Bill Chan 所说,现在我们会使用 keypaths:

func f1<Value>(car: Car, keyPath: KeyPath<Car, Value>) {
    print(car[keyPath: keyPath])
}

f1(car: car, keyPath: \.doors)

我使用

NSObject
类型的原始答案如下。


在过去,人们会通过从

NSObject
进行子类化来使用 Objective-C 键值编码:

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

那么,

f1
函数可以是:

func f1(car: Car, property: String) {
    print(car.value(forKey: property))
}

f1(car, property: "doors")

1
投票

带有关键路径的解决方案:

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)
© www.soinside.com 2019 - 2024. All rights reserved.