Skip to content

Instantly share code, notes, and snippets.

@wildthink
Last active March 30, 2020 20:34
Show Gist options
  • Save wildthink/68838db8a3ab55d67d529d459296f395 to your computer and use it in GitHub Desktop.
Save wildthink/68838db8a3ab55d67d529d459296f395 to your computer and use it in GitHub Desktop.
Swift Structs vs Paramaterized Enums

Swift Structs vs Parameterized Enums

There seems to be preference for choosing enums with parameters over Structs. Personally I've always been annoyed by inability of different components to extend an "enumerated" set of values, not to mention the extra work to extract enumerated values as needed (but explained here).

Both Swift structs and enums create a namespace that guides autocompletion. But what I really like about using structs is the ability to easily prototypes, instances providing default values.

With the addition of callAsFunction(...) building on prototypes is even easier.

struct Shop {
    var name: String
    var type: String
    
    func callAsFunction(_ clone_name: String) -> Shop {
        var clone = self
        clone.name = clone_name
        return clone
    }
    
    static var cheers = Shop(name: "Cheers", type: "bar")
    static var bar = Shop(name: "<bar>", type: "bar")
    static var cafe = Shop(name: "<cafe>", type: "cafe")

    static func custom(_ name: String, type: String) -> Shop {
        Shop(name: name, type: type)
    }
}

func printShops(_ shops: Shop...) {
    for shop in shops {
        print (shop.name, shop.type)
    }
}

printShops(.cheers, .custom("Jake's", type:"saloon"), .bar("Joe's Pub"), .cafe("Cool Cafe"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment