Swift Enums

So today I used enums for the first time and I’ll try to describe the process.  Let’s say you’re dealing with an app that deals with five different brands of cars – Fords, Volvos, Chevrolets, Auidis and Hondas.  You know that those car brands will be referenced over and over again.  You’ll also have to have an array of them somewhere and maybe store user preferences about them (maybe listing all the brands the user prefers).  Enums can make your life a lot easier.  So let’s make one:

enum CarBrand {
 case Ford, Volvo, Chevrolet, Auidi, Honda
 }

It’s that easy.  But there’s a lot more we can do.  So now we have a type – “CarBrand.”  Xcode will autocomplete for us when we begin typing CarBrand and give us the five options.  We’ve also limited the amount of errors because they will always be completed.  Also, if we add something or get rid of one of the brands we just do it in one place, wherever we typed the enum.

 

Still to come, functions within enums and CustomStringConvertible protocol (for printing or converting to a string).

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>