Swift Syntax
Introduction
Swift syntax forms the foundation of Swift programming, establishing the rules for how code must be written to be valid and executable. Understanding Swift's syntax is essential for anyone looking to develop applications for iOS, macOS, watchOS, or tvOS. In this guide, we'll explore the fundamental syntax elements of Swift, providing you with the knowledge needed to write clean, efficient, and error-free code.
Swift was designed to be modern, safe, and expressive. Its syntax is clean and concise, making it relatively easy to learn while offering powerful features for experienced developers. Whether you're new to programming or coming from another language, mastering Swift syntax will enable you to build amazing apps for Apple platforms.
Basic Syntax Elements
Comments
Comments allow you to include non-executable text in your code to provide explanations or documentation.
// This is a single-line comment
/*
This is a multi-line comment
that spans several lines
*/
// MARK: - Section Name
// Used to organize code in Xcode
Semicolons
Unlike many other programming languages, Swift doesn't require semicolons at the end of statements, although they are optional if you want to write multiple statements on a single line.
let name = "Swift" // No semicolon needed
let language = "Swift"; let year = 2014 // Semicolons used to separate statements on the same line
Variables and Constants
Constants (let)
Constants are declared using the let
keyword. Once a value is assigned to a constant, it cannot be changed.
let maximumLoginAttempts = 3
// maximumLoginAttempts = 4 // This would cause an error
Variables (var)
Variables are declared using the var
keyword and can be changed after they're declared.
var currentLoginAttempt = 0
currentLoginAttempt = 1 // This is valid because currentLoginAttempt is a variable
Type Annotations
Swift uses type annotations to be explicit about the kind of values a constant or variable can store.
let welcomeMessage: String = "Hello, world!"
var age: Int = 30
var pi: Double = 3.14159
var isLoggedIn: Bool = false
Type Inference
Swift can often infer the type of a variable based on the value assigned to it, eliminating the need for explicit type annotations.
let name = "John" // Swift infers this is a String
let age = 25 // Swift infers this is an Int
let temperature = 98.6 // Swift infers this is a Double
let isActive = true // Swift infers this is a Bool
Data Types
Swift offers several built-in data types:
Integers
let minValue = Int.min // Minimum value of Int
let maxValue = Int.max // Maximum value of Int
// Specific integer sizes
let int8Value: Int8 = 127 // -128 to 127
let uint8Value: UInt8 = 255 // 0 to 255
let int16Value: Int16 = 32767 // -32768 to 32767
let uint16Value: UInt16 = 65535 // 0 to 65535
Floating-Point Numbers
let float: Float = 3.14159 // 32-bit floating-point number
let double: Double = 3.141592653589793 // 64-bit floating-point number (default)
Booleans
let isCompleted: Bool = true
let isWorking: Bool = false
if isCompleted {
print("Task is completed!")
}
Strings
let greeting = "Hello"
let name = "Swift"
let welcomeMessage = greeting + ", " + name + "!" // String concatenation
let interpolatedMessage = "\(greeting), \(name)!" // String interpolation
print(welcomeMessage) // Output: Hello, Swift!
print(interpolatedMessage) // Output: Hello, Swift!
Characters
let singleCharacter: Character = "A"
let emoji: Character = "😀"
for character in "Swift" {
print(character)
}
// Output:
// S
// w
// i
// f
// t
Collections
Arrays
Arrays store ordered lists of values of the same type.
// Array declaration
var numbers: [Int] = [1, 2, 3, 4, 5]
var fruits = ["Apple", "Banana", "Orange"] // Type inference
// Accessing array elements
print(fruits[0]) // Output: Apple
// Modifying arrays
fruits.append("Mango")
fruits.insert("Pear", at: 1)
fruits.remove(at: 0)
print(fruits) // Output: ["Pear", "Banana", "Orange", "Mango"]
Dictionaries
Dictionaries store key-value pairs.
// Dictionary declaration
var airports: [String: String] = ["NYC": "New York", "LAX": "Los Angeles"]
var states = ["CA": "California", "NY": "New York"] // Type inference
// Accessing and modifying dictionaries
print(airports["NYC"] ?? "Unknown") // Output: New York
airports["SFO"] = "San Francisco"
airports["NYC"] = nil // Remove a key-value pair
print(airports) // Output: ["LAX": "Los Angeles", "SFO": "San Francisco"]
Sets
Sets store unique values in no particular order.
// Set declaration
var colors: Set<String> = ["Red", "Green", "Blue"]
var numbers: Set = [1, 2, 3, 4, 5] // Type inference
// Adding and removing elements
colors.insert("Yellow")
colors.remove("Red")
// Set operations
let primaryColors: Set = ["Red", "Blue", "Yellow"]
let secondaryColors: Set = ["Green", "Purple", "Orange"]
let availableColors = primaryColors.union(secondaryColors)
Operators
Arithmetic Operators
let sum = 5 + 3 // 8
let difference = 10 - 4 // 6
let product = 3 * 7 // 21
let quotient = 20 / 5 // 4
let remainder = 10 % 3 // 1
// Compound assignment operators
var value = 5
value += 3 // value is now 8
value *= 2 // value is now 16
Comparison Operators
let a = 5
let b = 10
a == b // false (equal to)
a != b // true (not equal to)
a < b // true (less than)
a > b // false (greater than)
a <= b // true (less than or equal to)
a >= b // false (greater than or equal to)
Logical Operators
let isRaining = true
let isCold = false
!isRaining // false (NOT operator)
isRaining && isCold // false (AND operator)
isRaining || isCold // true (OR operator)
if isRaining && !isCold {
print("It's raining but not cold.")
} // Output: It's raining but not cold.
Range Operators
// Closed range: includes both endpoints
for i in 1...5 {
print(i)
}
// Output: 1 2 3 4 5
// Half-open range: excludes the upper endpoint
for i in 1..<5 {
print(i)
}
// Output: 1 2 3 4
// One-sided ranges
let names = ["Anna", "Brian", "Charlie", "Diana"]
for name in names[2...] {
print(name)
}
// Output: Charlie Diana
for name in names[..<2] {
print(name)
}
// Output: Anna Brian
Control Flow
Conditionals
If-Else Statements
let temperature = 25
if temperature <= 0 {
print("It's freezing!")
} else if temperature <= 10 {
print("It's cold!")
} else if temperature <= 20 {
print("It's cool.")
} else if temperature <= 30 {
print("It's warm.")
} else {
print("It's hot!")
}
// Output: It's warm.
Switch Statements
Swift's switch statements are powerful and don't fall through by default.
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
// Output: Is it a spicy red pepper?
Loops
For-In Loop
// Looping through a range
for index in 1...5 {
print("Index is \(index)")
}
// Looping through an array
let fruits = ["Apple", "Banana", "Orange"]
for fruit in fruits {
print("I like \(fruit)")
}
// Looping through a dictionary
let heights = ["Taylor": 1.78, "John": 1.82, "Bob": 1.70]
for (name, height) in heights {
print("\(name) is \(height) meters tall")
}
While Loop
var countdown = 5
while countdown > 0 {
print("\(countdown)...")
countdown -= 1
}
print("Blast off!")
// Output:
// 5...
// 4...
// 3...
// 2...
// 1...
// Blast off!
Repeat-While Loop
Similar to do-while loops in other languages, the code block will execute at least once.
var num = 1
repeat {
print("Number is \(num)")
num += 1
} while num <= 3
// Output:
// Number is 1
// Number is 2
// Number is 3
Control Transfer Statements
// continue skips the current iteration
for number in 1...10 {
if number % 2 == 0 {
continue // Skip even numbers
}
print(number)
}
// Output: 1 3 5 7 9
// break exits the loop
for number in 1...10 {
if number > 5 {
break // Exit the loop when number is greater than 5
}
print(number)
}
// Output: 1 2 3 4 5
Functions
Basic Function Declaration
func greet(person: String) -> String {
return "Hello, \(person)!"
}
let greeting = greet(person: "John")
print(greeting) // Output: Hello, John!
Functions with Multiple Parameters
func greet(person: String, alreadyGreeted: Bool) -> String {
if alreadyGreeted {
return "Hello again, \(person)!"
} else {
return "Hello, \(person)!"
}
}
print(greet(person: "Anna", alreadyGreeted: true))
// Output: Hello again, Anna!
Functions without Return Values
func sayHello(to person: String) {
print("Hello, \(person)!")
}
sayHello(to: "Dave") // Output: Hello, Dave!
Functions with Default Parameter Values
func greet(person: String, greeting: String = "Hello") -> String {
return "\(greeting), \(person)!"
}
print(greet(person: "Emily")) // Output: Hello, Emily!
print(greet(person: "Emily", greeting: "Hi")) // Output: Hi, Emily!
Variadic Parameters
func calculateAverage(of numbers: Double...) -> Double {
var total = 0.0
for number in numbers {
total += number
}
return numbers.isEmpty ? 0 : total / Double(numbers.count)
}
print(calculateAverage(of: 1, 2, 3, 4, 5)) // Output: 3.0
Practical Examples
Building a Simple Calculator
func calculator(a: Double, b: Double, operation: String) -> Double {
switch operation {
case "+":
return a + b
case "-":
return a - b
case "*":
return a * b
case "/":
if b == 0 {
print("Error: Division by zero")
return 0
}
return a / b
default:
print("Error: Unsupported operation")
return 0
}
}
// Using our calculator
let result1 = calculator(a: 10, b: 5, operation: "+")
let result2 = calculator(a: 10, b: 5, operation: "-")
let result3 = calculator(a: 10, b: 5, operation: "*")
let result4 = calculator(a: 10, b: 5, operation: "/")
print("Addition: \(result1)") // Output: Addition: 15.0
print("Subtraction: \(result2)") // Output: Subtraction: 5.0
print("Multiplication: \(result3)") // Output: Multiplication: 50.0
print("Division: \(result4)") // Output: Division: 2.0
Creating a Temperature Converter
func convertTemperature(value: Double, from inputUnit: String, to outputUnit: String) -> Double {
var celsius: Double = 0
// Convert input to Celsius
switch inputUnit.lowercased() {
case "celsius", "c":
celsius = value
case "fahrenheit", "f":
celsius = (value - 32) * 5/9
case "kelvin", "k":
celsius = value - 273.15
default:
print("Error: Unsupported input unit")
return 0
}
// Convert Celsius to output unit
switch outputUnit.lowercased() {
case "celsius", "c":
return celsius
case "fahrenheit", "f":
return celsius * 9/5 + 32
case "kelvin", "k":
return celsius + 273.15
default:
print("Error: Unsupported output unit")
return 0
}
}
// Using the temperature converter
let freezingF = convertTemperature(value: 32, from: "f", to: "c")
print("32°F is \(freezingF)°C") // Output: 32°F is 0.0°C
let boilingC = convertTemperature(value: 100, from: "c", to: "f")
print("100°C is \(boilingC)°F") // Output: 100°C is 212.0°F
let roomTempC = convertTemperature(value: 20, from: "c", to: "k")
print("20°C is \(roomTempC)K") // Output: 20°C is 293.15K
Summary
In this comprehensive guide, we've covered the fundamental syntax elements of Swift:
- Comments and basic syntax structure
- Variables and constants with type annotations and inference
- Common data types including numbers, strings, and collections
- Operators for arithmetic, comparison, and logical operations
- Control flow statements for conditionals and loops
- Function declarations with parameters and return values
Understanding these foundational elements will enable you to build increasingly complex and powerful Swift applications. Swift's clear syntax and type safety help prevent common programming errors while encouraging readable and maintainable code.
Additional Resources and Exercises
Resources
Exercises
-
Variable Practice: Create variables for a person's profile including name, age, height, and whether they are a student. Print a sentence using string interpolation that incorporates all these variables.
-
Collection Manipulation: Create an array of your favorite movies. Add a new movie, remove one, and find a specific movie in the array. Then create a dictionary mapping movie titles to their release years.
-
Control Flow Challenge: Write a function that takes an integer and returns "Fizz" if the number is divisible by 3, "Buzz" if divisible by 5, "FizzBuzz" if divisible by both, and the number as a string otherwise.
-
Function Builder: Create a function called
repeatAction
that takes a string message and a number, then prints the message that many times. -
Calculator App: Extend the calculator example to include additional operations like exponents, square root, and modulus. Add error handling for invalid operations.
By working through these exercises, you'll reinforce your understanding of Swift syntax and develop practical coding skills that will serve as a foundation for more advanced Swift programming.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)