【问题标题】:Enum Simplicity in SwiftSwift 中的枚举简单性
【发布时间】:2020-06-19 22:46:02
【问题描述】:

我有以下枚举并且它有效。但是,有没有一种方法可以简单地更改 Int 并使其成为 String ,然后直接分配?

下面是不是很罗嗦? Companies(rawValue: httpMethod.self.rawValue)!Companies.stringValue 相比

如何调用以下命令来获取字符串值?

public enum Companies: String {
  case oil = "OIL"
  case tech = "TECH"
  case government = "GOVERNMENT"
  case restaurant = "RESTAURANT"
}

以下作品!

public enum Companies: Int {
  case oil
  case tech
  case government
  case restaurant

  var stringValue: String {
    switch self {
    case .oil:
      return "OIL"
    case .tech:
      return "TECH"
    case .government:
      return "GOVERNMENT"
    case .restaurant:
      return "RESTAURANT"
    }
  }
}

我可以直接拨打Companies.stringValue

【问题讨论】:

  • “但是为什么下面的方法不起作用?”。它确实有效。事实上,您甚至可以删除分配,它仍然有效。
  • 对不起@matt,我已经解决了我的问题。我很抱歉。
  • this answer 怎么样:使用enum Companies: CustomStringConvertible 并添加var description: String 而不是stringValue
  • 我还是不明白这一点。请提供真实的用例。
  • enum Companies: String, CustomStringConvertible { case oil, tech, government, restaurant public var description: String { rawValue.uppercased() } }

标签: swift


【解决方案1】:

请试试这个:

public enum Companies: String {
 case oil
 case tech
 case government
 case restaurant
 }
 let c = Companies.oil
 print(c.rawValue)

【讨论】:

    【解决方案2】:

    将计算属性添加到您的枚举中

    public enum Companies: Int {
        case oil
        case tech
        case government
        case restaurant
    
        var string: String {
            "\(self)".uppercased()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多