Can an enum contain another enum values in Swift?
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
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