code, coding, web

100 Days of SwiftUI – Day 3 & Day 4

We’re moving on to more complex types now which are used to group similar data together.

We cover how to declare arrays, dictionaries, sets and enums in Day 3 and look at what each is best suited to in terms of data storage. Covering these programming basics, a lot of what I learned at university is starting to come back to me, which is good. The key thing for me here is to try and get familiar with the Swift syntax.

Day 4 moves on to using type annotations when declaring constants and variables. Normally Swift can infer what the type of a thing is based on what you initially assign to it, but sometimes you want to initialise a thing either without assigning a value or with a value that could be one thing or another. In those cases you need to be explicit about what type it is using a type annotation.

Checkpoint 2

At the end of Day 4 we have Checkpoint 2. For this we need to:

  1. Create an array of strings.
  2. Print out the number of elements in the array.
  3. Print out the number of unique elements in the array.

Part 3 of this challenge is the interesting bit. I’m assuming I achieve this by converting the initial array into a set, since sets don’t allow duplicates. This seems to work.

import Cocoa

// Create an array (including a duplicate)
let albums = ["Pablo Honey", "The Bends", "OK Computer", "Pablo Honey"]

// Print the number of items in the array
print("There are \(albums.count) albums in the array.")

// Convert array to set by passing the array into a set constant
let albumsSet = Set(albums)

//Print the number of items in the set
print("There are \(albumsSet.count) albums in the set.")