【问题标题】:Create own / custom class object创建自己的/自定义的类对象
【发布时间】:2021-02-14 03:50:08
【问题描述】:

是否可以创建我自己的可以选择的对象?例如在一个函数中:

struct MyCustomType {
let id = 178
let reg = Expression<String?>(“reg”)

}


func runThis(enter: MyCustomType)
{
   print(enter)
}

基本上在调用 runThis 函数时,我想选择 id 或 reg。不是它的价值,而是像这样从 Id 和 reg 中选择:

runThis(enter: id)
//print 178

【问题讨论】:

  • 基本上你想使用通用值?
  • 基本上我想选择进入我的函数而不是通用的。因此,例如,您只能选择(这个,那个,然后)。一个可以是日期,一个是 Int,一个是 String。
  • 你回答你自己的问题,你想选择通用

标签: swift function class object struct


【解决方案1】:

不确定您的最终目标是什么,但您可以在此处使用 KeyPath

struct MyCustomType {
    let id = 178
    let reg = "Expression<String?>(“reg”)"
    let date = Date()

    func runThis<T>(enter: KeyPath<MyCustomType, T>)
    {
        print(self[keyPath: enter])
    }
}

例子

let x = MyCustomType()

x.runThis(enter: \.id)
x.runThis(enter: \.reg)
x.runThis(enter: \.date)

【讨论】:

  • 谢谢,这正是我要找的,KeyPath!
猜你喜欢
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-26
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
相关资源
最近更新 更多