Can an enum contain another enum values in Swift?

前端 未结 2 1556
感动是毒
感动是毒 2020-12-20 13:48

I\'d like to share some enum properties. Something like:

enum State {
  case started
  case succeeded
  case failed
}

enum ActionState {
  include State //          


        
相关标签:
2条回答
  • 2020-12-20 14:13

    Details

    • Swift 4, 3
    • Xcode 10.2.1 (10E1001), Swift 5 (Last revision of this post)

    Solution

    enum State {
        case started, succeeded, failed
    }
    
    enum ActionState {
        case state(value: State), cancelled
    }
    
    class Action {
        var state: ActionState = .state(value: .started)
        func set(state: State) { self.state = .state(value: state) }
        func cancel() { state = .cancelled }
    }
    

    Full Sample

    Do not to forget to paste the solution code

    import Foundation
    
    extension Action: CustomStringConvertible {
        var description: String {
            var result = "Action - "
            switch state {
                case .state(let value): result += "State.\(value)"
                case .cancelled: result += "cancelled"
            }
            return result
        }
    }
    
    let obj = Action()
    print(obj)
    obj.set(state: .failed)
    print(obj)
    obj.set(state: .succeeded)
    print(obj)
    obj.cancel()
    print(obj)
    

    Result

    //Action - State.started
    //Action - State.failed
    //Action - State.succeeded
    //Action - cancelled
    
    0 讨论(0)
  • 2020-12-20 14:20

    I had to validate the User License document. Which had two side - front and back. Depending upon the validation document could either be valid or invalid. Also UX was such that it would be active state or inactive state with corresponding colors to display. I ended up making following enum.

    public enum Validity {
        case pending(_ selectState: SelectState)
        case valid(_ selectState: SelectState)
        case invalid(_ selectState: SelectState)
    
        enum SelectState {
          case active(_ side: Side)
          case inactive(_ side: Side)
    
          enum Side {
            case front
            case back
          }
        }
      }
    

    Which can be referred as -

    public var validity: Validity = Validity.pending(.active(.front))

    I wish if could have been more clean like - Validity.pending.active.front but this is so far the solution for Enum inside of another enum can be.

    Swift 5.1, Xcode 11.4.1

    0 讨论(0)
提交回复
热议问题