【问题标题】:How to get the enumeration's name instead of the case's name in swift? [duplicate]如何快速获取枚举名称而不是案例名称? [复制]
【发布时间】:2017-08-20 02:42:07
【问题描述】:

现在我需要一种方便的方法来获取枚举本身的名称吗?这是一个例子。

enum SimpleEnum {
    case firstCase
    case secondCase
    case thirdCase
}
let simpleEnum: SimpleEnum = .firstCase
print("\(simpleEnum)") // return the "firstCase", but I want "SimpleEnum"

我知道下面的代码会起作用。

enum SimpleEnum: CustomStringConvertible {
    case firstCase
    case secondCase
    case thirdCase

    var description: String { return "SimpleEnum" }
}
let simpleEnum: SimpleEnum = .firstCase
print("\(simpleEnum)") // Ok, it return "SimpleEnum"

但是,我只想要一种通用方式,而不是为每个枚举键入“SimpleEnum”。

【问题讨论】:

  • type(of: simpleEnum)
  • 就是这样。我不知道 type(of:) 的存在,因为它是一个运算符,xcode 不会提示我。谢谢。

标签: swift syntax


【解决方案1】:

您可以通过调用type(of:) 从枚举案例中获取类型对象。然后,您可以通过调用 String.init(describing:) 将其转换为字符串:

let simpleEnum: SimpleEnum = .firstCase
let enumName = String(describing: type(of: simpleEnum))

如果您想从类型中获取类型名称,可以这样做:

let enumName = String(describing: SimpleEnum.self)

【讨论】:

  • type(of:) 正是我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-07
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 2012-12-28
  • 1970-01-01
相关资源
最近更新 更多