My Swift Programming Journey

Understanding Variables in Swift

Variables in Swift are used to store information that can be used and changed throughout your code. You define a variable using the var keyword followed by a name and a type. For example:

var greeting: String = "Hello, World!"

In this example, greeting is a variable of type String, and it's initially set to "Hello, World!". You can change its value later in the code.

Using Constants with let

Constants are similar to variables but their values cannot be changed once they are set. Use the let keyword to define a constant. For example:

let pi = 3.14159

Here, pi is a constant representing the value of π. Once defined, the value of pi cannot be changed, ensuring that it remains constant throughout your code.

Data Types in Swift

Swift has various data types to store different kinds of values. Here are some common ones:

  • Int: Represents whole numbers, e.g., let age: Int = 25
  • Double: Represents floating-point numbers, e.g., let height: Double = 5.9
  • String: Represents a sequence of characters, e.g., let name: String = "Alice"
  • Bool: Represents a boolean value, either true or false, e.g., let isLoggedIn: Bool = true

Swift Code Snippet: Simple Arithmetic

This code snippet demonstrates basic arithmetic operations in Swift:

let a = 10
let b = 5
let sum = a + b
let difference = a - b
let product = a * b
let quotient = a / b

This code initializes two integer constants a and b, then calculates their sum, difference, product, and quotient.

Swift Code Snippet: String Concatenation

This snippet shows how to concatenate strings in Swift:

let firstName = "John"
let lastName = "Doe"
let fullName = firstName + " " + lastName

Here, two string constants, firstName and lastName, are concatenated to form fullName.

Swift Code Snippet: Conditional Statement

This example illustrates a simple conditional statement using an if-else structure:

let score = 85

if score >= 90 {
    print("A")
} else if score >= 80 {
    print("B")
} else {
    print("C or lower")
}

The code checks the value of score and prints the corresponding grade based on the conditions.

Swift Code Snippet: Looping with For-In

This snippet demonstrates a basic loop using the for-in structure:

let numbers = [1, 2, 3, 4, 5]

for number in numbers {
    print(number)
}

This code loops through each element in the numbers array and prints it.

Optionals in Swift

Optionals in Swift allow variables to have a value or be nil. They are defined using a question mark ? after the type. For example:

var optionalName: String? = "John Doe"
optionalName = nil // Now the variable can be nil

To safely access the value of an optional, you can use optional binding or optional chaining.

Swift Code Snippet: Optional Binding

Optional binding is a safe way to unwrap an optional value. Here's an example:

var optionalName: String? = "John Doe"

if let name = optionalName {
    print("Hello, \(name)")
} else {
    print("No name provided")
}

If optionalName contains a value, it is assigned to name and the code inside the if block runs. Otherwise, the else block is executed.

Swift Code Snippet: Functions

Functions are reusable blocks of code that perform specific tasks. Here's a simple function that adds two numbers:

func add(a: Int, b: Int) -> Int {
    return a + b
}

let sum = add(a: 5, b: 3)
print(sum) // Output: 8

This function takes two integers as parameters and returns their sum.

Swift Code Snippet: Classes and Structures

Classes and structures are used to define custom data types. Here's an example of a simple structure:

struct Person {
    var firstName: String
    var lastName: String
}

let person = Person(firstName: "John", lastName: "Doe")
print(person.firstName) // Output: John

Structures in Swift can have properties and methods, just like classes. The main difference is that structures are value types, while classes are reference types.

Journal Entry 2

Journal Entry 3

Swift Code Snippet: Enumerations

Enumerations define a common type for a group of related values and enable you to work with those values in a type-safe way. Here's an example:

enum CompassPoint {
    case north
    case south
    case east
    case west
}

var direction = CompassPoint.north
direction = .east // Changing the value of direction

Enumerations can also have associated values and methods.

Swift Code Snippet: Protocols

Protocols define a blueprint of methods, properties, and other requirements for a particular task or functionality. Here's an example:

protocol Greetable {
    var name: String { get }
    func greet()
}

struct Person: Greetable {
    var name: String
    func greet() {
        print("Hello, \(name)")
    }
}

let person = Person(name: "John")
person.greet() // Output: Hello, John

In this example, the Greetable protocol requires a name property and a greet method. The Person structure conforms to this protocol by implementing the required elements.

First Entry 7/30/24

Starting my swift programming language journey and want to keep a small journal that i can use to display my thoughts and things that i learn. I hope to keep this updated as I work on more things swift. My main goal is to have a good understanding of the swift programming language a year from now,as i have to balence learning Swift along with Python for my classes at school.

Swift Project: To-Do List App

For a practical project, let's build a simple To-Do List app. This app will allow users to add and delete tasks.

Here's a basic outline:

  • Create a Task class or struct to represent a task.
  • Use an array to store tasks.
  • Implement functions to add and delete tasks.
  • Display the list of tasks in the console.
struct Task {
    var title: String
    var isCompleted: Bool
}

class ToDoList {
    private var tasks: [Task] = []

    func addTask(title: String) {
        let newTask = Task(title: title, isCompleted: false)
        tasks.append(newTask)
    }

    func removeTask(at index: Int) {
        if index < tasks.count {
            tasks.remove(at: index)
        }
    }

    func listTasks() {
        for (index, task) in tasks.enumerated() {
            print("\(index + 1). \(task.title) - \(task.isCompleted ? "Completed" : "Pending")")
        }
    }
}

let myToDoList = ToDoList()
myToDoList.addTask(title: "Finish Swift project")
myToDoList.addTask(title: "Study for exams")
myToDoList.listTasks()
myToDoList.removeTask(at: 0)
myToDoList.listTasks()

Swift Project: Basic Calculator

This project involves creating a simple calculator that can perform basic arithmetic operations like addition, subtraction, multiplication, and division.

Key features:

  • Input handling for two numbers and an operator.
  • Perform the calculation based on the input operator.
  • Display the result.
class Calculator {
    func add(_ a: Double, _ b: Double) -> Double {
        return a + b
    }

    func subtract(_ a: Double, _ b: Double) -> Double {
        return a - b
    }

    func multiply(_ a: Double, _ b: Double) -> Double {
        return a * b
    }

    func divide(_ a: Double, _ b: Double) -> Double? {
        if b != 0 {
            return a / b
        } else {
            return nil
        }
    }
}

let calculator = Calculator()
if let result = calculator.divide(10, 2) {
    print("Result: \(result)")
} else {
    print("Cannot divide by zero.")
}