【问题标题】:Swift: How to implement an enum of array of StringsSwift:如何实现字符串数组的枚举
【发布时间】:2020-08-16 13:01:53
【问题描述】:

我正在尝试实现这样的字符串数组枚举

import UIKit

enum EstimateItemStatus: Int, [String] {
    case Pending
    case OnHold
    case Done

    var description: [String] {
        switch self {
        case .Pending:
            return ["one", "Two"]
        case .OnHold:
            return ["one", "Two"]
        case .Done:
            return ["one", "Two"]
        }
    }
}

print(EstimateItemStatus.Pending.description)

但是我收到了这个错误:

error: processArray.playground:3:31: error: multiple enum raw types 'Int' and '[String]'
enum EstimateItemStatus: Int, [String] {
                         ~~~  ^

你们中的任何人都知道如何修复此错误以使枚举工作?

非常感谢您的帮助。

【问题讨论】:

    标签: ios enums swift5.2 xcode11.4


    【解决方案1】:

    从枚举声明中删除 [String]

    enum EstimateItemStatus: Int {
        case Pending
        case OnHold
        case Done
    
        var description: [String] {
            switch self {
            case .Pending:
                return ["one", "Two"]
            case .OnHold:
                return ["one", "Two"]
            case .Done:
                return ["one", "Two"]
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以像这样将枚举的原始值设置为String

      enum EstimateItemStatus: String {
          case Pending: "Pending"
          case OnHold: "OnHold"
          case Done: "Done"
      }
      

      然后像这样访问它

      print(EstimateItemStatus.Pending.rawValue)
      

      【讨论】:

        【解决方案3】:

        我们无法确定您实际需要什么,因为您没有使用IntArray。您可能想要2-String 元组原始值:

        enum EstimateItemStatus: CaseIterable {
          case pending
          case onHold
          case done
        }
        
        extension EstimateItemStatus: RawRepresentable {
          init?( rawValue: (String, String) ) {
            guard let `case` = ( Self.allCases.first { $0.rawValue == rawValue } )
            else { return nil }
        
            self = `case`
          }
        
          var rawValue: (String, String) {
            switch self {
            case .pending:
              return ("pending", "?")
            case .onHold:
              return ("onHold", "?")
            case .done:
              return ("done", "✅")
            }
          }
        }
        
        EstimateItemStatus( rawValue: ("onHold", "?") )?.rawValue // ("onHold", "?")
        EstimateItemStatus( rawValue: ("Bootsy Collins", "?") ) // nil
        [("done", "✅"), ("pending", "?")].map(EstimateItemStatus.init) // [done, pending]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-12
          • 1970-01-01
          • 2021-01-21
          • 1970-01-01
          • 1970-01-01
          • 2014-07-23
          相关资源
          最近更新 更多