iOS AI Agents with Claude
Swift Basics
Getting Started with Swift
Swift is the modern programming language created by Apple. It's designed to be safe, fast, and expressive, making it the primary language for building apps across all Apple platforms, from your iPhone to your Mac.
Swift is a powerful and intuitive programming language developed by Apple for iOS, macOS, watchOS, and tvOS app development.
Think of learning Swift like learning the grammar and vocabulary of a spoken language. Before you can write a novel (or build an app), you need to know how to form sentences. Let's start with the basic vocabulary and grammar of Swift.
Variables, Constants, and Types
In programming, we need places to store information. These containers are called variables and constants. The main difference is that a variable's value can change, while a constant's value, once set, cannot.
Use
letto declare a constant (a value that won't change). Usevarto declare a variable (a value that can change).
Here’s how you declare them:
let maxLoginAttempts = 3 // A constant
var currentLoginAttempts = 0 // A variable
currentLoginAttempts = 1 // This is okay
// maxLoginAttempts = 4 // This would cause an error!
Every piece of data in Swift has a type. This helps prevent bugs by ensuring you don't accidentally try to add a word to a number. Swift is smart and can often figure out the type on its own, a feature called type inference. Some basic types include:
String: For text, like"Hello, world!".Int: For whole numbers, like10or-5.Double: For numbers with decimal points, like3.14159.Bool: For true or false values, eithertrueorfalse.
let welcomeMessage = "Welcome!" // Swift infers this is a String
let score = 100 // Swift infers this is an Int
let pi = 3.14 // Swift infers this is a Double
var isUserLoggedIn = false // Swift infers this is a Bool
Making Decisions and Repeating Tasks
Programs aren't just lists of instructions executed in order. They need to respond to different situations and repeat actions. This is handled by control flow statements.
To make a decision, you can use an if statement. It checks if a condition is true and runs a block of code accordingly. You can add an else block to run code if the condition is false.
let temperature = 75
if temperature > 65 {
print("It's a nice day!")
} else {
print("It's a bit chilly.")
}
To repeat a task, you use loops. A for-in loop is perfect for running a piece of code for each item in a collection, like an array of numbers.
// An array of scores
let scores = [88, 92, 75, 100, 95]
// Loop through each score
for score in scores {
print("The score is \(score)")
}
Organizing Code with Functions and Objects
As programs grow, you need ways to keep them organized and reusable. Functions and object-oriented programming are key tools for this.
function
noun
A self-contained chunk of code that performs a specific task. You can 'call' a function to run its code.
Functions let you package up a task, give it a name, and run it whenever you need. They can take in data (parameters) and send data back (a return value).
// This function takes a name (a String)
// and returns a greeting (also a String).
func greet(person: String) -> String {
let greeting = "Hello, " + person + "!"
return greeting
}
// Call the function and print the result
print(greet(person: "Alice"))
Object-oriented programming (OOP) takes organization a step further. It lets you model real-world things by bundling related data (properties) and behavior (methods) into a single unit. In Swift, these units are often created using class or struct.
Imagine you're building an app for a library. You could model a book as an object. A book has properties (like a title and author) and methods (actions it can perform, like checking itself out).
class Book {
// Properties
var title: String
var author: String
var isCheckedOut = false
// A special function to create a new Book instance
init(title: String, author: String) {
self.title = title
self.author = author
}
// A method
func checkOut() {
isCheckedOut = true
print("\(title) has been checked out.")
}
}
// Create an instance of the Book class
let theHobbit = Book(title: "The Hobbit", author: "J.R.R. Tolkien")
// Call its method
theHobbit.checkOut()
Mastering these fundamentals—variables, control flow, functions, and objects—is the first major step toward building powerful and complex applications.
Ready to check your understanding? Let's see what you've learned.
In Swift, what is the fundamental difference between a variable declared with var and a constant declared with let?
If you write the following line of code in Swift, what data type will be inferred for the constant bookTitle?
let bookTitle = "The Swift Programming Language"
With these basics, you have the foundation needed to explore more advanced Swift concepts and start building your own projects.