Wednesday, 23 December 2015

Swift Enums and Protocols

I'm trying to clear out my inbox before Christmas and I noticed an emails to myself entitled 'Enum question. Add protocol to enum?'.

The short answer is yes. The longer one. Take the following protocol

protocol Foo
{
func f() -> Void
}

A simple enum can be created that implements it:

enum Test: Foo
{
case One
func f()
{
print("Hello")
}

}

So the following short program:

let baz = Test.One

baz.f()

generates the output:

Hello
Program ended with exit code: 0

The protocol can also be implemented by extension so the following is equivalent and produces the same results:

extension Test: Foo
{
func f()
{
print("Hello")
}
}

It's not surprising that Swift's enum types support protocols. Off the top of my head I can't think of any clever reasons why you'd have enums implement a protocol. Given an enum is a first class type in Swift then it makes perfect sense. In fact it's documented on page 424 in The Swift Programming Language.

No comments: