Logic & Fundamentals: Swift Core

Logic & Fundamentals: Swift Core

Logic & Fundamentals: Swift Core

Writing programs is the art of giving instructions to a machine. To do this, you need to understand how to control the flow of execution: how code makes decisions, repeats tasks, and organizes data.

1. Core Data Types

Swift is a strongly typed language, which means every variable must have a defined type. The most common ones are:

  • String: Textual data, e.g., "Hello, Developer".
  • Int: Whole numbers, e.g., 42.
  • Double: Decimal numbers, e.g., 3.14159.
  • Bool: Boolean values, either true or false.

2. Control Flow: Making Decisions

Programs need to adapt based on conditions. Swift provides simple tools for decision-making:

  • if and else: Executes a block of code only if a condition is met.
  • switch: A powerful replacement for multiple if conditions, ensuring you handle every possible scenario.
let score = 85

if score >= 90 {
    print("Excellent!")
} else if score >= 80 {
    print("Good job!")
} else {
    print("Keep practicing!")
}

3. Repeating Tasks: Loops

Instead of writing the same code repeatedly, we use loops to iterate over collections or run blocks of code multiple times.

  • for-in: Used to loop over a range or a collection of items (like an array).
  • while: Runs a block of code as long as a boolean condition remains true.
// Iterating over a range of numbers
for number in 1...5 {
    print("Step \(number)")
}

4. Organizing Data: Arrays & Dictionaries

Collections allow you to group multiple values together:

  • Arrays: An ordered list of items. Elements are accessed by their index starting at 0.
  • Dictionaries: A collection of key-value pairs, where you look up a value using a unique key (similar to looking up a word in a real dictionary).
// Array Example
var shoppingList = ["Apples", "Bananas", "Oranges"]
shoppingList.append("Grapes")
print(shoppingList[0]) // Output: Apples

// Dictionary Example
let capitals = ["India": "New Delhi", "USA": "Washington D.C."]
print(capitals["India"]) // Output: Optional("New Delhi")

Checkpoint Task

Go to our Syntax Sandbox and write a Swift program that calculates the sum of all numbers in an array. Define an array of integers: let numbers = [5, 12, 8, 20, 7]. Loop through the numbers, add them to a running total, and print the final sum. The output should be 52.

Ready for more depth?

Master these concepts with our structured technical roadmap.

View Roadmap