【问题标题】:Swift Use enum with custom answerSwift 使用带有自定义答案的枚举
【发布时间】:2016-05-17 15:16:48
【问题描述】:

我想在 Swift 中使用枚举来处理一些事情,比如学校的科目。如果有人想要另一个不在枚举中的主题,他可以输入主题作为自定义值。 例如:

enum Subjects {
    case Math
    case German
    case French
    case Chemistry
    case another //type in which it is
}

var example1 = Subjects.Math
var example2 = Subjects.another("Physics")

【问题讨论】:

  • 在 Swift 参考中查找“具有关联值的枚举”。

标签: swift enums associated-value


【解决方案1】:

这是使用关联值的完美示例

enum Subjects {
  case Math
  case German
  case French
  case Chemistry
  case Other(String)
}

var example1 = Subjects.Math
var example2 = Subjects.Other("Physics")

switch example2 {
  case .Other(let type) : print(type)
  default: break
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-09
    • 2021-09-22
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多