Hacking With SwiftUI, Day 5

I managed to get a lesson done on one out of two days this weekend, so I’m counting that as a success. Back in the saddle for Day 5 of my journey through SwiftUI. Today’s series of lessons is all about Conditions!

Conditions

The first lesson today was about testing conditionals, i.e. – if statements. This was probably the most straightforward lesson today, because from here on it gets pretty hectic. Essentially, you just write a simple sentence that says “if something matches this condition, then do this”. It’s pretty easy! An easy example is this:

var mySanity = "gone"

if mySanity == "gone" {
    print("Sorry, dude. You lost your marbles!")
}

Since the variable mySanity is equal to the string “gone”, the codes prints out the message “Sorry, dude. You lost your marbles!”.

Easy enough, though this is yet another example of me constantly getting tripped up by the difference between parentheses, braces, and brackets.

Multiple conditions

The next step in today’s lesson was about testing for multiple conditions, using if else statements. Pretty straightforward expansion on just regular conditions. They seem pretty readable when there are only a couple things to check, but I have a feeling the next block of this lesson is going to be about a better way to solve for situations with lots of conditions to check because I can see this getting unwieldy already.

Switch

From here, we moved on to switch statements. Switch statements are designed specifically for enums, and they must be exhaustive. You can set a default case that handles anything not explicitly covered in the cases you’re writing, though, so you don’t have to make a case for literally every possible scenario. By default switch statements also stop at the first case that runs, but you can set fallthrough after your statements to have it continue running the next cases. Paul has a great example of using switch statements to print out the 12 Days of Christmas:

let day = 5
print("My true love gave to me…")

switch day {
case 5:
    print("5 golden rings")
case 4:
    print("4 calling birds")
case 3:
    print("3 French hens")
case 2:
    print("2 turtle doves")
default:
    print("A partridge in a pear tree")
}

Without fallthrough, it’s going to stop at the first case. By adding fallthrough after each case it will continue running the rest of the code, printing out the entire lyrics as expected. Find of a fun example!

Ternary Operator

Finally, we wrapped it up with a quick runthrough of the ternary operator. The ternary operator is just a way for us to do either/or behavior on a given condition. Scott Michaud has a great tweet about remembering how to use the ternary operator.

This still feels a little superfluous to me, but Paul says that as we get deeper into actually using SwiftUI we’re going to find some situations where ternary operators become critically important. So…hurray, I guess?

Anyway, this was a fairly in-depth lesson about several different pieces of Swift functionality, and it’s kinda neat to already start to see how some of this stuff fits together and might be getting used in apps I use regularly. The examples for switch statements, in particular, have me wondering if that’s how an app like Carrot does some of its functionality based on weather condition.

Tomorrow’s lesson is about loops and then has another checkpoint, so it feels like we’re getting ready to dive into some more complex features of the language pretty quickly. Can’t wait!

Hacking With SwiftUI, Day 4

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)

Hacking With SwiftUI, Day 3

Here we are at Day 3 of Hacking With SwiftUI. Yesterday’s lesson was about Booleans and string interpolation, with a quick checkpoint thrown in at the end to make sure I was actually retaining the information from Day 1 and 2. Today’s lesson, by contrast, dives down a little deeper into more complex topics.

Arrays

Arrays are just a method of storing multiple pieces of data simultaneously. In Paul’s example, he uses it to store the names of the members of The Beatles, a series of temperatures, and the infamous numbers from Lost. You can read back data from a specific position in the array – called an “index” – and you can append data to the end of an array as long as it’s a variable. The untouchable nature of constants continues on, I guess.

Apparently, there are no restrictions on adding the same value multiple times, so you could have 27 “Ringos” in your array of Beatles members, but I assume there’s some solution to that so you don’t have duplicate data.

It seems noteworthy that you’re only allowed to add the same kind of data to an array, and you can’t use two different kinds of arrays together. So if I have an array containing nothing but strings, and an array containing nothing but integers, I can’t smash them together in code. Paul has a helpful example of this:

let firstBeatle = beatles[0]
let firstNumber = numbers[0]
let notAllowed = firstBeatle + firstNumber

The fact that you can do work on the data in an array with a simple command like array.count or array.sorted already seems useful, but I’m wondering why you wouldn’t want to just store them in the sorted format instead. I’m sure there’s some reason I will learn later on, but so far it’s super easy to modify or get basic info about the contents of an array and that seems helpful!

I scored 6/6 on the mini-test about Arrays, so apparently I absorbed something.

Dictionaries

TURNS OUT dictionaries are the solution I was looking for. This is where you can set all the magical key/value pairs that I’ve heard about forever, assign default values, and perform the same kind of operations on them that you can on arrays.

Nifty stuff!

One slight area of concern is that there appear to be even more rules about parentheses, brackets, commas, and colons now, which for someone who likes to read fast and try stuff out is going to be a painful lesson. I foresee many broken lines of code because I put a bracket instead of a brace, etc.

5/6 on the test for this one, so not too shabby.

Unfortunately, I did much worse on the “Dictionary Default Values” test, only scoring 8/12. Sure enough, my concern about reading too fast turned out to be true. At least two that I got wrong were about missing colons or trying to mix and match strings and integers. Ugh.

Sets and Enums

Luckily, I bounced back on the Sets and Enum tests. 6/6 on both! Enums seem to be very powerful since you’re strictly limiting the potential values that can be assigned to a var or constant. Paul Hudson quietly mentions in the additional reading at the end of today’s lesson:

As you progress, you’ll learn how Swift lets us add more functionality to enums – they are more powerful in Swift than in any other language I have seen.

Just telling me enough to keep me interested!

Tomorrow’s lesson is a short one, just type annotations and then a second checkpoint. My weekend is going to be hectic, but I’m hoping I can keep my streak alive.

Hacking With SwiftUI, Day 2

I haven’t written forever, but I feel like doing it may help keep me honest on this little self-improvement journey I’ve undertaken. I just started the delightful 100 Days of SwiftUI project by Paul Hudson, and I’m really digging it so far. He takes an overwhelming concept – learning Swift and SwiftUI from scratch – and, at least so far, breaks it down into easily digestible chunks that you just take one day at a time. It’s the classic “how do you eat an elephant” problem, but specifically for teaching a novice how to code.

Day 2’s lesson was shorter than Day 1, only focusing on Booleans and string interpolation. Importantly, though, this was the first “checkpoint”, which is a mini-review of the concepts covered so far. I vaguely remember some of these concepts from when I’ve toyed with code before, so today’s task was fairly easy.

Your goal is to write a Swift playground that:

  • Creates a constant holding any temperature in Celsius.
  • Converts it to Fahrenheit by multiplying by 9, dividing by 5, then adding 32.
  • Prints the result for the user, showing both the Celsius and Fahrenheit values.

Fairly straightforward, no?

Creating the initial constant is easy enough:

let celsius = 15.0

Creating the constant for the Fahrenheit conversion is also easy enough now that we have the Celsius constant. Some simple mathematical operators looks like this:

let fahrenheit = celsius * 9 / 5 + 32

I still get slightly tripped up by what does and does not require parentheses, but I think I’ll get used to it as I progress further. From what I can grok so far, I think I only need to do the slash + parentheses thing when trying to embed the value inside a string (see below).

The only remaining task is to print the output in a human-friendly format. I tossed in a degree symbol (°) for good measure and voila:

print("The current temperature is \(celsius)°, which is \(fahrenheit)° Fahrenheit." )

A quick click of the build and run button in Xcode and you get:

The current temperature is 15.0°, which is 59.0° Fahrenheit.

Easy enough. Let’s see what tomorrow brings.

Oh no.