Swift Basics: Complex Data Types
Arrays, Dictionaries, Sets, and Enums in Swift
Hi All, As I told in the last post I have started a #100DaysOfSwiftUI challenge this is my learning from Day 3. where I have learned about Complex data types in Swift Such as Arrays, Sets, Dictionaries, and Enums. Let's go through it once:
Complex Data Types
Let's Take a Look at the more complex data types that group data together in swift. So we have learned about simple data types like string, numbers, booleans, etc. in the last blog of mine take a look if you haven't seen it yet. So for complex data types, we want to group similar types of data in cases where we want the Name of your close friends or the Different temperature throughout the day, etc. cases. So to handle such scenarios we have Arrays, Dictionaries, Sets, and Enums each specialize in handling one of such cases let's go through them one by one.
Store and Retrieve Ordered Data in Arrays
It is almost common to have lots of data of similar type in a single place whether that is days in a week or name students in a class etc. In swift, we do these grouping by using Arrays. The array is their data type just like String, Int, and Double but rather handling one, two strings it can adapt to store as many. strings you want and it always holds the data in the order that we have stored it.
let's go through a few Array examples:
let temperature = [25.3, 23.33, 20. 09]
let students = ["Monkey", "Dog", "Cat"]
let scores = [98, 78, 92, 65]
As you can see in the above example array we are grouping temperatures or names students using Square Brackets [ ], and each data is separated by commas, and brackets open and close indicates the start and end of a group of data. Also, one point to be noted is as you can see in the example all the data group is of the same data type either it is Whole numbers or it is Strings so we can't group data of different data types they all should be of the same type.
Since we stored the data now let's try to retrieve those data from the arrays. so we can do it using the index numbers of items stored. Also, the index numbers always start from 0 not from 1. So get the first item in the array we should read it like this:
let students = ["Monkey", "Dog", "Cat"]
// To get first student name
print(students[0])
//To Get the 3rd student name
print(students[2]
So now let's try to start an empty array and append the data as we go on.
var scores = Array<Int>()
scores.append(95)
scores.append(100)
print(scores[1])
So as you see the above code I am defining an empty Array at the beginning in the next line I am appending the data as I want using the append() method. also, we can read data in the same way shown earlier but we have to make sure that we are trying to get the correct index value otherwise swift will through an array out of bounds exception.
There are a few more useful functionality offered by an array.
- First is using the .count method we can get the size of the array similar to the .count() method in the String.
- Second functionality is removing an item from an index using the remove(at: ) method the item from the index mentioned in at will be removed from an array or by using removeAll() we can remove all items from an array.
- we can check if any item is stored in an array using the contains() method which will return a boolean value based on if that item exists or not.
- we can sort the array using the sorted() method.
Store and Find Data in Dictionaries
Dictionaries and arrays are both ways of storing lots of data in one variable but they store them in different ways: Dictionaries use a Key to identify where we want to add data and in arrays, we just add them sequentially.
So let's just say like the form we collect a few fixed data from users like name, job title, and Location if we store them using the array then there is a chance that data could be stored in a different order or someone deletes one of those values. To handle such cases we use Dictionaries that store data in key-value pairs.
// Storing employee details using array
var employee = ["Coding Monkey", "Coder", "Monkey Land"]
print("Name: \(employee[0])")
print("Job title: \(employee[1])")
print("Location: \(employee[2])")
// Storing employee details using Dictionary
let employee = [
"name": "Coding Monkey",
"Job": "Coder",
"Location": "Monkey Land"]
print("Name: \(employee["name"])")
print("Job title: \(employee["Job"])")
print("Location: \(employee["Location"])")
So as you can see now using the key-value pairs we can store the data as we want and also we don't have to remember the index number we just have to know what data we want and its key name. Also, Keys can't duplicate if we try to use the same key twice the value associated with the key will get updated with the latest value.
Also, we provide default values in Dictionary in cases where no data is found for the expected key.
print(employee2["name", default: "Unknown"])
print(employee2["job", default: "Unknown"])
print(employee2["location", default: "Unknown"])
Sets for Fast Data Lookup
Both Sets and arrays are collections of data meaning that they hold multiple values inside a single variable. However, how they hold their value is what matters: Sets are unordered and cannot contain duplicates, whereas arrays retain their order and can contain duplicates.
Those two differences might seem small but they have an interesting side effect: because Sets don't need to store your object in the order you add them they can instead store them in a seemingly random order that optimizes them for fast retrieval so any query on collection set data provide results at a much faster rate than Arrays.
let people = Set(["Denzel Washington", "Tom Cruise", "Nicolas Cage", "Samuel L Jackson"])
As you can see we are creating an array then putting that array inside Set. it's the standard way of creating a set from fixed data. If we have duplicate data set will automatically remove those values, and it won't remember the exact order these details are stored in an array.
Another way to create a set is that is without fixed data like this:
var people = Set<String>()
people.insert("Denzel Washington")
people.insert("Tom Cruise")
people.insert("Nicolas Cage")
people.insert("Samuel L Jackson")
So like we used append() in the array we use insert() method in sets to add new data to the set.
create and use Enums
Enum is short for Enumerations- is a set of named values we can create and use in our code. We are going to use Enums in a great many ways in swift in future.
To demonstrate a use case of enum:
var direction = "North"
direction = "South"
//Then we might use direction for show sides like
direction = "Left"
// Or we use different case
direction = "NORTH"
As shown in the code we can expect any values for the variable direction. but if we expect values in specific ways then where the enums come in: they let us define a new data type with a handful of specific values that it can have. think of boolean there we can only have true or false we can't have "may be" or "probably" because that isn't in the range of values it understands. Enums are the same: we get to list up for the range of value it can have, and Swift will make sure you never make the mistake of using them.
So we can define the direction in this way using enum:
enum Direction {
case North
case South
case East
case West
}
and we use the enums instead of using string to assign value to variable.
var direction = Direction.North
direction = Direction.East
so if we by mistake use some other name in enum like for North if we provide north the Xcode will throw an error saying don't know this enum value. As we go on we will be using Enums more and more.
Conclusion
So I have learned on the Day 3 of 100 Days of SwiftUI that how to use Arrays, Sets, Dictionaries, Enums, and several functionalities offered by them and use cases for each.
Also, let me know if any mistakes are done in this blog/write-up I have done on Day 3 learning so I can fix my mistakes and improve my understandings.
Thank you.