Swift enums

I’ve started on the refactoring for Rock, paper, scissors. One of the things I didn’t like was using Ints to signal which shape (I’m calling the rock, or paper, or scissors hand shape a shape) was being handed around. The Int I was using was also the index into an array of the emoji’s – so if I did an off-by-one I was risking an out of bounds on the array.

I’m pleased with this solution:

If you’re a refugee from C, there’s a lot happening here:

1 – In C enums are actually int’s inside, and you can mess with which int goes with which value. In Swift, they can be any type, but the type is specified when you define the enum. They are extracted with .rawvalue

2 – The Swift String type is a beast. Yes it does emojis, and a lot of other very cool unicode stuff that has a cost.

3 – enums can have methods. I know right?

When I read the Swift book, I felt it was a travesty against nature for enums being allowed to have methods, but the code above felt like the most natural thing ever. I must be acclimatising.

Apart from eliminating the array out of bounds possibility, this also made the code more readable, and meant that I could remove the default case from all my switch statements.

source

I might not be happy with the name of this type – Shape. I have spend a bit of time thinking about it, and even looked up Rock Paper Scissors on Wikipedia to see what terminology they used. It’s meant to represent the shape of the hands made by the players in each round of the game. It felt unclear enough that I added a comment to make it clearer – a sure sign it’s not. It may change to FingerShape when I do the next lot of refactoring.

Leave a comment