100 Days of SwiftUI Learning — Day 3

Krishna
4 min readMay 3, 2022

Either you run the day or the day runs you

Agenda

Today the focus is on Collection Data types

  1. Arrays
  2. Dictionaries
  3. Sets
  4. Enums

Arrays

An array is an ordered list of items. An array can contain duplicates. Let us look at some examples to better understand the concept.

var letters = ["a","b","c","c"]
let numbers = [1,2,3]
var decimals = [1.1,2.2,3.33]

The list of elements that you want to declare as an array should be enclosed in []. Keep in mind that all the items from an Array should have the same data type. That means the following line will break your code and generate errors.

var data = ["a","b",3]

The position of an item in an array is called as index. The index of the first element is zero.

Creating an empty array

Swift offers us two methods to do this.

//Method 1
var nums = Array<Int>()
//Method 2
var nums = [Int]()

Remember, you can add elements of only one data type to an array. Use the data type while initializing an empty array. To add items to the array we will use append.

append

To add an item to the end of the array, we use .append.

var numbers = [1,2,3]
numbers.append(4)
numbers.append(5)

By using append, you can add only one item at a time. You can also use append to add one array to another.

var nums1 = [1,2,3]
var nums2 = [10,20,30]
nums1.append(contentsOf:nums2) //[1,2,3,10,20,30]

Using + operator

To add two arrays, you can use + operator.

var nums1 = [1,2,3]
var nums2 = [10,20,30]
var nums3 = nums1 + nums2 //[1,2,3,10,20,30]

count

This is used to get number of items in an array.

var nums = [1,2,3,4]
nums.count //4

remove

To remove an item from an array from a specific index.

var nums = [1,2,5,7]
nums.remove(at:2)
nums//[1,27]

removeAll

To remove all items of an array.

var nums = [1,2,3]
nums.removeAll()
nums //[]

Note: This will just remove the items in the array but not delete the array.

contains

To check if an item is present in the array. The result of the statement will be a boolean.

var nums = [1,2,3]
nums.contains(4) //false
nums.contains(1) //true

sorted

Using the sorted function will return a new sorted array by keeping the original array unchanged.

var nums = [1,2,5,3,4,6,1]
var nums2 = nums.sorted() //[1,1,2,3,4,5,6]

reversed

reversed() will not give you a reversed array but swift will remember it as a reversed collection. To better understand this let us see an example.

As you can see from the screenshot, when you assign letters.reversed() to a new variable, the variable remembers it as a reversed Collection of a base collection. In this example, letters is the base collection.

When you are actually going through the new collection i.e., letter2 then it will print the reverse order.

Dictionary

Dictionary is a key-value pair data type. Dictionary will not allow duplicate keys.

let constant_name = [
key:value
]

Values or data stored in a dictionary can be accessed using keys.

var employee = [
"name" : "krishna"
"age" : "25"
]
print(employee["name"]) // Optional("Krishna")

As the given key may or may not have a value in the dictionary, swift uses optionals. That means swift is saying us that there is a chance that there is no data present in the dictionary.

To avoid getting optional in the output, when we are using a key to access a value, we provide a default value. So, if data doesn’t exist the default value will be used.

var employee = [
"name" : "krishna"
"age" : "25"
]
print(employee["name", default:"Unknown"]) // "Krishna"
print(employee["location", default:"Unknown"]) // "Unknown"

Since, “location” doesn’t exist in the dictionary, “Unknown” is printed.

Note: All keys should be of same data type and all values should be of same data type. i.e., if the first pair is String:Int, all remaining pairs should also maintain same data type.

Create an empty dictionary

var variable_name = [String:String]()

Sets

Sets are unordered and does not allow duplicates.

To create a set from an array of data, follow below example.

let array_name = ["a","b","c"]
let set_name = Set(array_name)
//orlet set_name = Set(["a","b","c"])

If your array contains any duplicates, swift will automatically remove them.

Creating empty set.

var set_name = Set<data_type>()

insert

To add items to the set.

var people = Set<String>()
people.insert("Krishna")

Similar to Arrays, .contains(), .count, .sorted() can be used in sets.

enum

Enum will let us define a new data type with some specific values that can be used when using that data type.

Enum can be defined in two ways. Let us look at creating a data type Weekday

//Method 1: Using multiple case statements
enum Weekday {
case monday
case tuesday
case wednesday
case thursday
case friday
}
//Method 2: Using one case statementenum Weekday {
case monday, tuesday, wednesday, thursday, friday
}

Using the new data type is also very easy.

var day = Weekday.monday

As soon as you type the dot, swift will show you options that are available. In this case monday through friday.

Since you have initialized day as variable, you can change it’s value and it should be of type Weekday only as swift is a type safe language.

var day = Weekday.mondayday = .tuesday // The value gets changed to tuesday

That is everything for today’s study. See you tomorrow. Take care.

--

--