Default arguments in Swift enums

FYI: Default parameter values are now allowed after Swift 5.1. This answer only applies to versions of Swift before that.


This is a tricky one because you cannot have default values, you cannot have stored properties and you cannot repeat case names in enums. The best thing I can think to do is to create an init() and some semi-private cases.

enum SnapOperationQueuePriority {
    case Highest, High, Low, Default
}

enum SnapOperationQueue {
    case Highest, High, Normal, Low

    case _Highest(lowerThreshold: SnapOperationQueuePriority)
    case _High(lowerThreshold: SnapOperationQueuePriority, higherThreshold: SnapOperationQueuePriority)
    case _Normal(lowerThreshold: SnapOperationQueuePriority, higherThreshold: SnapOperationQueuePriority)
    case _Low(higherThreshold: SnapOperationQueuePriority)

    init(queue:SnapOperationQueue, lowerThreshold:SnapOperationQueuePriority = .Default, higherThreshold:SnapOperationQueuePriority = .Default) {
        switch queue {
        case .Highest:
            self = ._Highest(lowerThreshold: lowerThreshold == .Default ? .Highest : lowerThreshold)
        case .High:
            self = ._High(lowerThreshold: lowerThreshold == .Default ? .Low : lowerThreshold, higherThreshold: higherThreshold == .Default ? .High : higherThreshold)
        case .Normal:
            self = ._Normal(lowerThreshold: lowerThreshold == .Default ? .Low : lowerThreshold, higherThreshold: higherThreshold == .Default ? .High : higherThreshold)
        case Low:
            self = ._Low(higherThreshold: higherThreshold == .Default ? .Low : higherThreshold)
        default:
            self = queue

        }
    }
}

SnapOperationQueue.Normal
SnapOperationQueue(queue: .Normal)
SnapOperationQueue(queue: .High, lowerThreshold: .High, higherThreshold: .Highest)

This keeps old implementations valid and catches new ones made using init. In addition you might add a method like this to the enum:

func queue() -> SnapOperationQueue {
    switch self {
    case .Highest:
        return SnapOperationQueue(queue: .Highest)
    case .High:
        return SnapOperationQueue(queue: .High)
    case .Normal:
        return SnapOperationQueue(queue: .Normal)
    case Low:
        return SnapOperationQueue(queue: .Low)
    default:
        return self

    }

}

So that you can transform the old types of enum cases into the new, e.g. SnapOperationQueue.Normal.queue()


This is now possible starting with Swift 5.1 (Xcode 11)

See the feature proposal.