Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2015-09-26

Swift Design Pattern: Swift Enum's, the Switch statement and an alternative solution

I love the Swift Enum's. Full stop.

But working with enum's and the switch statement? I don't like that too much, tends to make the code pretty obscure. In Swift 2 there is the if case which is better, but still does not make my code very readable.

Luckily there is an alternative solution possible, what I would call the is-enum pattern:

Traditionally I would define an enum like:

enum ValueItem {
    case NULL
    case BOOL(Bool)
    case STRING(String)
    case NUMBER(NSNumber)
    case ERROR(code: String, reason: String)
}

Let's say I am interested in a number and bool and only then want to execute some code. I have the following possibilities:

    // Only for bool and number:
    
    switch val {
    case .BOOL, .NUMBER:
        // code
    default: break
    }

Or:
    // Only for bool and number:
    
    var boolOrNum: false
    if case .NUMBER = val { boolOrNum = true }
    if case .BOOL = val { boolOrNum = true }
    
    if boolOrNum {
        // code
    }


Neither of which is not very transparent imo. What I would like is this:

    if val.isBool || val.isNumber {
        // code
    }

Even the comment line is no longer needed, the code is completely self documenting.

The only thing we have to do to enable this is to add the corresponding var's to the enum declaration:

enum ValueItem {
    case NULL
    case BOOL(Bool)
    case STRING(String)
    case NUMBER(NSNumber)
    case ERROR(code: String, reason: String)
    
    var isNull: Bool {
        if case .NULL = self { return true }
        return false
    }
    var isBool: Bool {
        if case .BOOL = self { return true }
        return false
    }
    
    var isString: Bool {
        if case .STRING = self { return true }
        return false
    }

    var isNumber: Bool {
        if case .NUMBER = self { return true }
        return false
    }

    var isError: Bool {
        if case .ERROR = self { return true }
        return false
    }
}

Easy.

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment