首页 > 解决方案 > 在 Swift 中将结构重构为枚举

问题描述

今天有人评论了这段代码,并建议它会更好enum

typealias PolicyType = (filename: String, text: String)

struct Policy {
  static let first = PolicyType(filename: "firstFile.txt", text: "text in first file")
  static let second = PolicyType(filename: "secondFile.txt", text: "text in second file")
  static let third = PolicyType(filename: "thirdFile.txt", text: "text in third file")
}

let thirdPolicyText = Policy.third.text

有没有一种更高效、更可维护的方式来使用枚举来做到这一点?我的主要目标是可维护性。

以下是我想出的:

enum Policy: RawRepresentable {
  case one
  case two
  case three

  var rawValue: (filename: String, text: String) {
    switch self {
    case .one:
      return ("1", "policy 1 text")
    case .two:
      return ("2", "policy 2 text")
    case .three:
      return ("3", "policy 3 text")
    }
  }

  init?(rawValue: (filename: String, text: String)) {
    switch rawValue {
    case ("1", "policy 1 text"):
      self = .one
    case ("2", "policy 2 text"):
      self = .two
    case ("3", "policy 3 text"):
      self = .three
    default:
      return nil
    }
  }
}

至此,我已经弄清楚如何使用 astruct和 an实现类似的功能enum。如果有人回去更新它,这enum似乎需要更多的维护,而且更容易出错。Paul Hegarty 说不会崩溃的线路是你不写的线路,而且enum路线看起来和感觉都很麻烦。

enum走这条路线与一条路线相比有记忆优势struct吗?

完成后,我希望能够将 Policy 作为参数传递,如下所示:

func test(for policy: Policy) {
  print(policy.rawValue.filename)
  print(policy.rawValue.text)
}

test(for: Policy.first)

标签: iosswiftstructenums

解决方案


这是一种可能性。它有点长,但它是 Swifty:

enum Policy {
    case one, two, three

    var filename: String {
        switch self {
        case .one: return "Policy 1 name"
        case .two: return "Policy 2 name"
        case .three: return "Policy 3 name"
        }
    }

    var text: String {
        switch self {
        case .one: return "Policy 1 text"
        case .two: return "Policy 2 text"
        case .three: return "Policy 3 text"
        }
    }
}

目前 Swift 枚举的问题在于它们仅限于 RawValues。我最近遇到了和你类似的情况,我也尝试使用枚举而不是结构。我什至尝试了一个命名元组。但是,我最终使用了一个结构。


推荐阅读