100 Days of SwiftUI Checkpoint 1

100 Days of SwiftUI Checkpoint 1

Course Credit:

This blog post's content is based on the fantastic learning materials from Paul Hudson's 100 Days of SwiftUI course, available for free at Hacking with Swift.

The Core Building Blocks of Swift

  1. Variables (var) and Constants (let): Use let for values that won't change, and varfor values that will. Prefer let whenever possible to make your code safer and more predictable.
  2. Strings: Swift strings can hold text of any length, including emoji. Useful string functionalities include:
    • .count: Returns the number of characters.
    • .uppercased(): Converts the string to uppercase.
    • .hasPrefix() and .hasSuffix(): Check if a string starts or ends with specific text.
    • Multi-line Strings: Use three double quotes (""") at the beginning and end, each on its own line.
  3. Numbers (Int and Double):
    • Integers (Int): For whole numbers. They have functionality like .isMultiple(of:).
    • Doubles (Double): For decimal numbers (floating-point numbers). While good for decimals, they are not 100% accurate for precise calculations like money.
    • Arithmetic Operators: Swift supports standard operations like +-*/, and **.
    • Compound Assignment Operators: Shorthand operators like +=-=*=/=, etc.
  4. Booleans (Bool): Store simple true or false values.
    • .toggle(): Flips the boolean's value.
    • !: The logical NOT operator also flips a boolean's value.
  5. String Interpolation: A powerful way to create strings by embedding variables, constants, and expressions directly into them using \(...). This makes combining different types of data into a string much easier and more readable than concatenating with +.
import UIKit

// --- Variables and Constants ---

// Variables are like labeled storage containers where you can store information (data) in your program.
// Think of them as boxes with labels that hold different things, like tools in a toolbox or parts in an engine.
var greeting = "Hello, playground"
var name = "Ted"
name = "Rebecca"
name = "Keeley"

// Constants, declared with 'let', are values that cannot be changed once they are set.
// Prefer using 'let' as much as possible, as it helps Swift prevent mistakes by ensuring values remain fixed.
let character = "Daphne"

var playerName = "Roy"
print(playerName)

playerName = "Dani"
print(playerName)

playerName = "Sam"
print(playerName)

// --- Strings ---

let managerName = "Michael Scott ⭐️ 🥰"
let dogBread = "Samoyed"
let meaningOfLife = "How many roads must a man walk Down?"
let filename = "swift_intro.md"

// String properties and methods:
// '.count' returns the number of characters in a string.
print(managerName.count)
let nameLength = meaningOfLife.count
print(nameLength)

// If you ask Swift to read something it has (like a property), you don't need parentheses.
// But if you ask Swift to do work for you (like calling a method), you need them.
print(managerName.uppercased())

// Multi-line strings use triple quotes (""") and must have the opening and closing quotes on their own lines.
let multiLineString = """
Variables are like labeled storage containers where you can store information (data) in your program.
Think of them as boxes with labels that hold different things, like tools in a toolbox or parts in an engine.
"""
print(multiLineString)

// Checking for prefixes and suffixes:
print(multiLineString.hasPrefix("Variables"))
print(filename.hasSuffix(".md"))

// --- Numbers and Math ---

// Integers (whole numbers) are declared using 'Int'.
let score = 10
let reallyBig = 1000000000
// Underscores can be used to make large numbers easier to read; they don't affect the value.
let reallyBigEasyToRead = 1_000_000_000

// Basic arithmetic operators:
let lowerScore = score - 2
let higherScore = score + 2
let doubledScore = score * 2
let squaredScore = score * score
let halvedScore = score / 2

// Compound assignment operators combine an operation and assignment.
var counter = 10
// counter = counter + 5 (equivalent to the line below)
counter += 5
print(counter)

counter *= 2
counter -= 10
counter /= 2

// 'isMultiple(of:)' checks if a number is a multiple of another.
let number = 120
print(number.isMultiple(of: 3))
print(120.isMultiple(of: 3)) // Can also be called directly on a number literal.

// --- Booleans (True/False) ---

// Booleans store simple true or false values.
let newFileName = "Paris.jpg"
print(newFileName.hasSuffix(".jpg"))

let newNumber = 120
print(newNumber.isMultiple(of: 3))

let goodDogs = true
var gameOver = false
print(gameOver, "gameOver")
// '.toggle()' flips a boolean's value from true to false, or false to true.
gameOver.toggle()
print(gameOver, "gameOver")

let isMulpitle = 120.isMultiple(of: 3)

var isAuthenticated = false
// The '!' operator (logical NOT) flips a boolean's value.
isAuthenticated = !isAuthenticated
print(isAuthenticated, "isAuthenticated")
isAuthenticated = !isAuthenticated
print(isAuthenticated, "isAuthenticated")

// --- String Interpolation ---

// Strings can be joined together using the '+' operator.
let firstPart = "Hello"
let secondPart = " World!"
let greetingMessage = firstPart + secondPart

let people = "Haters"
let action = "Hate"
let pbf = people + " Gonna " + action

// To include double quotes within a string, escape them with a backslash (\").
let quote = "Then he tapped a sign saying \"Believe\" and walked away."

// String interpolation allows you to embed variables and expressions directly into a string.
// Use a backslash and parentheses: "\(variableNameOrExpression)".
let name2 = "Taylor"
let age2 = 30
let message2 = "Hello, my name is \(name2) and I am \(age2) years old."
print(message2)

let number2 = 11
// Swift cannot directly add an Integer and a String.
// The two ways below will work by converting the integer to a string or using string interpolation.
let missionMessage = "Appolo " + String(number2) + " landed on the moon."
let missionMessage2 = "Appolo \(number2) landed on the moon."

// You can also perform calculations directly within string interpolation.
print("5 x 5 = \(5 * 5)")

/* My Checkpoint 1
Your goal is to write a Swift playground that:

1. Creates a constant holding any temperature in Celsius.
2. Converts it to Fahrenheit by multiplying by 9, dividing by 5, then adding 32.
3. Prints the result for the user, showing both the Celsius and Fahrenheit values.
4. TIP If you type shift + option + 8 you get the degree symbol °
*/

let celsius = 25.0
let fahrenheit = celsius * 9 / 5 + 32
print(celsius, "°C")
print(fahrenheit, "°F")
print("The tempeture is \(fahrenheit)° Fahrenheit.")

/*
--- Recap of Swift Basics ---

Several fundamental concepts in Swift:

1.  **Variables (`var`) and Constants (`let`):** Use `let` for values that won't change, and `var` for values that will. Prefer `let` whenever possible to make your code safer and more predictable.

2.  **Strings:** Swift strings can hold text of any length, including emoji. Useful string functionalities include:
    * `.count`: Returns the number of characters.
    * `.uppercased()`: Converts the string to uppercase.
    * `.hasPrefix()` and `.hasSuffix()`: Check if a string starts or ends with specific text.
    * **Multi-line Strings:** Use three double quotes (`"""`) at the beginning and end, each on its own line.

3.  **Numbers (`Int` and `Double`):**
    * **Integers (`Int`):** For whole numbers. They have functionality like `.isMultiple(of:)`.
    * **Doubles (`Double`):** For decimal numbers (floating-point numbers). While good for decimals, they are not 100% accurate for precise calculations like money.
    * **Arithmetic Operators:** Swift supports standard operations like `+`, `-`, `*`, `/`, and `**`.
    * **Compound Assignment Operators:** Shorthand operators like `+=`, `-=`, `*=`, `/=`, etc.

4.  **Booleans (`Bool`):** Store simple `true` or `false` values.
    * `.toggle()`: Flips the boolean's value.
    * `!`: The logical NOT operator also flips a boolean's value.

5.  **String Interpolation:** A powerful way to create strings by embedding variables, constants, and expressions directly into them using `\(...)`. This makes combining different types of data into a string much easier and more readable than concatenating with `+`.

*/