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, eithertrueorfalse.
2. Control Flow: Making Decisions
Programs need to adapt based on conditions. Swift provides simple tools for decision-making:
ifandelse: Executes a block of code only if a condition is met.switch: A powerful replacement for multipleifconditions, 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.