swiftenumsassociated-value

Swift Use enum with custom answer


I want to use an enum in Swift for some stuff like subjects in school. And if someone wants to have another subject, which isn't in the enum, he can type in the subject as a custom value. For example:

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")

Solution

  • That's a perfect example to use an associated value

    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
    }