Introduction to enums in Swift

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
and enumeration is a user-defined data type which consists of a set of related values the keyword enum is used to define enumerated data types since the keyword is short for enumeration I am gonna pronounce it even but you may wish to say enum as is often heard hi my name is Stewart Lynch and this is an introductory video that will be followed in the weeks to come with videos of practical examples to reinforce the concept but first before we can apply it we need to learn the basics and in this video we'll cover the basic enumeration syntax including raw and associated values and we'll explore the power of the switch statement and including functions within our enum definition if this is something you want to learn then keep watching the way I'm going to approach this is to take a look at how one might have approached a problem that is much better when using an enum so let's consider this array which is the days of the week all string elements if we want to create a variable or a constant for what is often called hump day the middle of the work week we'll see that that's the fourth value in our array but the third index since arrays start at 0 so we can define hump date a and I'll use a to indicate it's an array value as a rainy days of week 3 looking at our code we have no idea what that day is until we run the code and then we see that it's Wednesday and this is where enums have a great advantage let's create an enum that will represent the days of the week and this is a finite set of values which is a good choice for an enum the simplest way to create an enum is to simply define the enum and list all possible cases and just like defining a struct or a class we start with the keyword enum and then our curly brackets or braces and within these braces we can take a shortcut and use a single case keyword followed by all cases separated by commas you'll notice that it's common practice to use lowercase letters all of our cases now when we want to define our hump day we can just do let hump day equal days of week dot and then note as soon as we enter the dot were presented with all of our options to pick from so we can just pick Wednesday since we use lowercase words in our cases for days of week it would be nice to have them capitalized as they should be when we want to print it out no problem with our array because we can use any one of these string functions on our element for example let's say our Wednesday element in our array was lower cased we could simply then just do hump day not capitalized to have a display with a capital letter but when we try to apply a similar type function like capitalized to our hump day which is our enum constant we get an error our email has no member capitalized if you check out the quick help for our two constants we see that hump day is one of the cases of our enum while hump day a is defined as a string what we can do though is define a type for our email in this case we can see that all of our cases is a string by adding that to our declaration this still doesn't solve our problem but we can specify the raw value of our string case and what that will do is stringify if you like the case and then we can capitalize it so hump day dot raw value dot capitalized we can if we like add functions to our enum so that if we always want to display our day as a capitalized value we can add a function like this by creating a function that returns a string that is a raw value capitalized and then when we want to display the date we can just do empty dot display day instead you the switch construct in Swift is a very powerful construct let's say we don't know what day that we company is and we want to check when that is and perhaps print out something to the console using our array it's very cumbersome to construct the switch statement let's create a function called what to do that takes in a string which will be one of our days of the week and then check what it is through a switch statement and return a string response we start with switch day which is just a generic string and we have to build all cases and recreate a return string response so let me speed up my typing here to save some time even after we account for all cases Swift has no idea if you've covered them all because hump day a is just a string as far as its concerned so we'll let Xcode fix this by adding in the default case and we'll return an appropriate response let's test this and find out what to do on our hump day a constant perhaps you didn't expect that response well it's because we have lowercase W for Wednesday and the comparison didn't match it should have been a capital W this is a problem when using strings it's too easy to make mistakes let's look at how we would handle this with an enum we'll start by creating our function in the same way but this time we'll pass in a days of week enum now when we start switch day right away we get a warning that switch must be exhaustive with the option of letting Xcode fix it for us and just like that all options are presented with no default because our enum must be one of the seven values let's just copy in the same results with lightning speed of my typing there's no way you can make a mistake now when we call the function our parameter must be a days of week and restricted to choosing from one of those days of week cases it doesn't mean that you don't ever use a default in a switch statement when using an enum though let's create another function to check if a day is on a weekend funk is it a weekend and pass in a day that is a days of week and return a bool this time we can switch on day and for the two cases that our weekends return true and this time we do use default to cover all the other five cases and simply return false and yes indeed Saturday is on a weekend for the next part fitted a new playground and have added the same days of league enum as in the last playground but instead of using a comma between cases have separated each out onto a single line and each with its own case keyword our enum still has raw values of type string that will default to the string representation of our case but we can assign a different raw value for each for example if we wanted to have the raw values be the abbreviations of each we could do it this way so now doing something like let's sundae equals days of week Sunday raw value it will display the abbreviation if we fail to assign a specific raw value then it will default back to the string representation of the case let's consider this enum called numbers and we're going to create five cases representing the integers 1 through 5 and instead of declaring this enum as a string type let's use int now if we want to know the integer value of case 1 for example you might think we can just do let num equals numbers dot 1 but this num is just the case of numbers if we want a number we'll need to use the numbers dot one dot raw value however this generates a zero and not a one that we'd want when we can solve this in two ways we could create a function that returns an int and in the body increments the raw value by one and now instead of specifying the raw value we can use the real value and say num equals numbers dot one dot real value but there's a better way Imams have a way of auto setting the raw values as we saw in the last example we can assign a specific value for each case but there's a bonus here if the numbers assigned are sequential we only need to assign the first one and it will increment accordingly so we can say case 1 equals 1 and this works for intz doubles and floats so we can see that numbers dot v dot raw value will indeed give us the integer 5 whenever you start at it will increment from there so if we start at 1 equals negative 2 then numbers dot v dot raw value will be positive 2 you can loop over all cases in an enum but in order to do that you must simply have your enum conform to the case iterable protocol and by doing so it opens up a whole host of new options so for example if we do this for our days of week we can now see that our type days of week has a new static dot all cases property and we see that it's actually a collection of all the cases so we can do things like days of week dot all cases dot count and we find as expected we have seven cases and since it's a collection we can use other collection higher-order functions like map let's say we want to extract an array of strings that is the capitalization of all of our days of week raw values but cap days equals days a week dot all cases dot map and then using shorthand notation dollar zero raw value dot uppercase now if you don't understand higher-order functions like map I suggest you watch my video series on higher-order functions and I'll leave a link in the notes below we can loop through each of the items in a foreign loop as well as long as we add the dot all cases static property two days of week we can print that if the day of the week is a Saturday or Sunday it's a weekend but I work day otherwise the possibilities are endless with this power and I want to finish off this introductory video by taking a look at associative values each enum case can have an Associated value and unlike the raw value associated values can be of different types and the one caveat is that enums with associated values can't have raw values for example we can construct an enum for activities with four cases sleep game run and eat we don't care about how long a person sleeps but we'd like to know the name of the game that they play so we'll associate the name as a string if he runs we'd like to know the distance in kilometers as an INT and if he eats we'd like to record what is he which is also a string now with this enum we can create an activity struct that will have three properties one for morning afternoon and evening and all of them are of type activity so we can record for example Johnny's activities by creating an instance of activity and when we select an appropriate activity were required to enter a value if there's an associative value and in this case he eats eggs in the morning runs 10k in the afternoon and sleeps in the evening note that sleep doesn't require any additional parameter of course if you really want to tighten up your data entry you can define another enum that would be a list of approved games for example let's create an enum of valid games with only two cases checkers and chess and then specify that the associative value of the game be a valid game this would mean that when our user selects a game activity they give it only enter one of the two approved types well that completes this introduction to enums and as mentioned in the introduction the next few weeks of my videos I'll intersperse a number of practical examples to show you how I use enums in my development perhaps learn more about swift swift UI and even more about enews thanks for watching I have lots of other videos available and in the queue as well so please check out the rest of my channel you can also visit my website to see the apps that I have available on the App Store and visit my github page to see what I have available as public repositories if you like what you've seen give it a thumbs up and subscribe to my channel and ring the bell to get notified when I post new videos I'm most active on Twitter so please follow me there as well to find out what else I'm up to thanks for watching
Info
Channel: Stewart Lynch
Views: 2,254
Rating: undefined out of 5
Keywords: swift, enum, Xcode, iOS
Id: 8ocSpsSlvJg
Channel Id: undefined
Length: 15min 21sec (921 seconds)
Published: Sun May 31 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.