Swift Programming Language
Introduction to Swift
Swift is Apple's modern programming language for iOS, macOS, watchOS, and tvOS development. It offers modern features, safety, and high performance.
Key Features:
- Type safety
- Optionals
- Protocol-oriented programming
- Modern syntax
- Memory safety
- Value types
Language Basics
Variables and Constants
// Variables and Constants
let constant = "This cannot be changed" // Immutable
var variable = "This can be changed" // Mutable
// Type inference
let number = 42 // Int
let double = 42.0 // Double
let string = "Hello" // String
let bool = true // Bool
// Explicit types
let explicitInt: Int = 42
let explicitDouble: Double = 42.0
// Optionals
var optionalString: String?
var unwrappedString = optionalString ?? "default"
// Optional binding
if let unwrapped = optionalString {
print(unwrapped)
}
// Guard statement
func processAge(_ age: Int?) {
guard let validAge = age, validAge >= 18 else {
print("Invalid age")
return
}
print("Processing age: \(validAge)")
}
// Collections
var array = [1, 2, 3]
var dictionary = ["key": "value"]
var set: Set = [1, 2, 3]
Functions and Closures
// Function with parameters and return type
func greet(name: String, age: Int) -> String {
return "Hello, \(name)! You are \(age) years old."
}
// Function with default parameter
func greet(name: String, greeting: String = "Hello") -> String {
return "\(greeting), \(name)!"
}
// Variadic parameters
func sum(_ numbers: Int...) -> Int {
return numbers.reduce(0, +)
}
// Inout parameters
func swapValues(_ a: inout Int, _ b: inout Int) {
let temp = a
a = b
b = temp
}
// Closures
let multiply: (Int, Int) -> Int = { $0 * $1 }
let result = multiply(4, 2) // 8
// Trailing closure syntax
let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.map { $0 * 2 }
// Capture lists
var count = 0
let increment = { [count] in
print("Counting from \(count)")
}
Advanced Features
Classes and Structs
// Class definition
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func birthday() {
age += 1
print("Happy Birthday! Now \(age) years old!")
}
}
// Struct definition
struct Point {
var x: Double
var y: Double
mutating func moveBy(x: Double, y: Double) {
self.x += x
self.y += y
}
}
// Protocols
protocol Vehicle {
var wheelCount: Int { get }
func start()
func stop()
}
// Protocol extension
extension Vehicle {
func describe() -> String {
return "Vehicle with \(wheelCount) wheels"
}
}
// Class conforming to protocol
class Car: Vehicle {
let wheelCount = 4
func start() {
print("Starting car")
}
func stop() {
print("Stopping car")
}
}
// Property wrappers
@propertyWrapper
struct Clamped {
private var value: T
let range: ClosedRange
init(wrappedValue: T, range: ClosedRange) {
self.range = range
self.value = min(max(wrappedValue, range.lowerBound),
range.upperBound)
}
var wrappedValue: T {
get { value }
set { value = min(max(newValue, range.lowerBound),
range.upperBound) }
}
}
Concurrency
Async/Await and Actors
// Async function
func fetchUser(id: String) async throws -> User {
let data = try await networkClient.fetch(url)
return try JSONDecoder().decode(User.self, from: data)
}
// Async sequence
func fetchItems() async throws -> AsyncStream- {
AsyncStream { continuation in
for i in 1...5 {
continuation.yield(Item(id: i))
try? await Task.sleep(nanoseconds: 1_000_000_000)
}
continuation.finish()
}
}
// Task group
func fetchAllUsers(ids: [String]) async throws -> [User] {
try await withThrowingTaskGroup(of: User.self) { group in
for id in ids {
group.addTask {
try await fetchUser(id: id)
}
}
var users: [User] = []
for try await user in group {
users.append(user)
}
return users
}
}
// Actor
actor ChatRoom {
private var messages: [Message] = []
func send(_ message: Message) {
messages.append(message)
}
func fetchMessages() -> [Message] {
messages
}
}
iOS Development
UIKit Example
class ViewController: UIViewController {
private let tableView = UITableView()
private var items: [Item] = []
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
private func setupUI() {
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(
equalTo: view.topAnchor),
tableView.leadingAnchor.constraint(
equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(
equalTo: view.trailingAnchor),
tableView.bottomAnchor.constraint(
equalTo: view.bottomAnchor)
])
}
private func loadData() {
Task {
do {
items = try await fetchItems()
tableView.reloadData()
} catch {
showError(error)
}
}
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "Cell",
for: indexPath
)
let item = items[indexPath.row]
cell.textLabel?.text = item.title
return cell
}
}
SwiftUI
SwiftUI Views
struct ContentView: View {
@State private var name = ""
@State private var isShowingAlert = false
var body: some View {
NavigationView {
Form {
Section(header: Text("User Info")) {
TextField("Name", text: $name)
Button("Submit") {
isShowingAlert = true
}
}
}
.navigationTitle("Profile")
.alert("Hello", isPresented: $isShowingAlert) {
Button("OK", role: .cancel) {}
} message: {
Text("Hello, \(name)!")
}
}
}
}
struct ItemRow: View {
let item: Item
var body: some View {
HStack {
VStack(alignment: .leading) {
Text(item.title)
.font(.headline)
Text(item.subtitle)
.font(.subheadline)
.foregroundColor(.secondary)
}
Spacer()
if item.isCompleted {
Image(systemName: "checkmark.circle.fill")
.foregroundColor(.green)
}
}
.padding()
}
}
// MVVM with SwiftUI
class ItemViewModel: ObservableObject {
@Published var items: [Item] = []
@Published var isLoading = false
@Published var error: Error?
func loadItems() {
isLoading = true
Task {
do {
items = try await fetchItems()
} catch {
self.error = error
}
isLoading = false
}
}
}
SwiftUI Features:
- Declarative syntax
- Automatic state management
- Live previews
- Cross-platform support
- Animations
- Combine integration