It’s the dawn of the second day for my 100 Days of SwiftUI. This day was relatively short, but still very fun to go through. I also came across my first “Checkpoint”, an independent code exercise. Let’s dive right in!
A boolean is one of the handful of basic data types in Swift and like the others, it’s important to understand how it works. A boolean is used to store either a true or false. The declaration of a boolean works in the same way as the data types discussed in day 1 and can either be a variable or a constant.
var gameOver = false; // This will print false. print(gameOver) // The .toggle() function toggles a boolean to true/false gameOver.toggle( // This would now be true. print(gameOver) let myNumber = 15 print(myNumber.isMultiple(of: 5)) // This will print true, because 15 is a multiple of 5.
String interpolation sounds complicated, at least I thought so. However, it just means combining multiple strings together. From what I’ve gathered, this wasn’t very intuitive in older versions of Swift, but it has been vastly improved in Swift 5 onward.
Just like with an integer or double, a string can be combined by using the + operator. However, while what will work, due to the nature of how Swifts handles this operator, it’s not quite as fast or efficient as doing it this way:
let myName = "Darryl" let myAge = 26 print("Hi! My name is \(myName) and I'm \(myAge) years old." // Output: Hi! My name is Darryl and I'm 26 years old.
If you’d like to know why Swift has string interpolation, check out Paul Hudson’s article on the matter. It’s a short read and provides a link to another one of his articles that details advanced ways of using string interpolation.
SwiftUI Checkpoint 1
The first checkpoint was quite fun. The task was simple: convert temperatures from Celsius to Fahrenheit. The steps involved:
- Create a constant holding any temperature in Celsius
- Convert it to Fahrenheit by multiplying by 9, dividing by 5, then adding 32
- Print the result, showing both the Celsius and Fahrenheit values
Using what I’ve learned in day 1 and 2, the solution I came to worked as expected.
let celsiusTemp = 28.0 let fahrenheitTemp = (celsiusTemp * 9 / 5 + 32) let conversionMessage = "It's currently \(celsiusTemp)° Celsius, which equals \(fahrenheitTemp)° Fahrenheit." print(conversionMessage) // It's currently 28.0° Celsius, which equals 82.4° Fahrenheit.
And that was it for day 2! From here on out, the difficulty will start to ramp up bit by bit, so I’m looking forward to it. Let me know what you think about the first checkpoint and my solution. It’s always good to get some feedback!
100 Days of SwiftUI – Day 2 – Booleans & String Interpolation