Well hey, welcome to Day 4 of my journey through SwiftUI. Today’s lesson is a short one, focusing exclusively on Type Annotations, then wrapping up with the second Checkpoint. The type annotations lesson was brief; essentially just laying out that you can specify the data type for a given array or whatnot ahead of time, instead of relying on Swift’s type inferencing. Seems useful, I suppose.
Today’s checkpoint was a little bit tougher, mostly because it’s intentionally left fairly open-ended without much direction. The task is to create an array of items – it doesn’t matter what – then print the total number of items and the total number of unique items.
Sets immediately jump out as being useful here, since they automatically de-duplicate data for you. I made an array of Taylor Swift albums, because hey why not? I created the array using this:
let albums = ["Taylor Swift", "Taylor Swift", "1989", "Fearless", "Speak Now", "Red", "1989", "Reputation", "Lover", "Folklore", "Evermore", "Fearless (Taylor's Version)", "Red (Taylor's Version" ]
As you can see, I put a couple duplicates in there, just so I have something to actually de-duplicate with the set in a minute.
I then confirmed the total count of albums in the array using this little snippet:
print (albums.count)
Which confirms that there are 13 albums in my little array.
Next, I need to create a Set with the same data to de-duplicate and get my unique count. My first inclination was to just create the Set manually just like I did the array above. Thankfully, Paul Hudson included this little hint on the Checkpoint 2 page:
Sets can be made from arrays using Set(someArray)
Using that, I created the Set out of the array with this little snippet:
let uniques = Set(albums)
Running print (uniques) shows that the Set was created successfully by passing in the array like that – hurray for less typing!
Finally, I just need to get the total count of unique items, which is easy enough with the .count feature I learned a couple days ago:
print (uniques.count)
11 unique albums. Success! The entire block of code I used is below:
let albums = ["Taylor Swift", "Taylor Swift", "1989", "Fearless", "Speak Now", "Red", "1989", "Reputation", "Lover", "Folklore", "Evermore", "Fearless (Taylor's Version)", "Red (Taylor's Version" ] print (albums.count) let uniques = Set(albums) print (uniques) print (uniques.count)
