← Back to Software

Swift Documentation

iOS and macOS development with Swift

Getting Started

Swift is Apple's powerful programming language for iOS, macOS, watchOS, and tvOS development.

Hello World

import Foundation print("Hello, World!")

Variables and Constants

// Constants (immutable) let name = "Swift" let version = 5.9 // Variables (mutable) var count = 0 var isActive = true // Type annotations let message: String = "Hello" let numbers: [Int] = [1, 2, 3, 4, 5]

Functions and Closures

// Basic function func greet(name: String) -> String { return "Hello, \(name)!" } // Function with multiple parameters func add(_ a: Int, to b: Int) -> Int { return a + b } // Closures let numbers = [1, 2, 3, 4, 5] let doubled = numbers.map { $0 * 2 } // Trailing closure syntax UIView.animate(withDuration: 0.3) { view.alpha = 0.5 }

Classes and Structures

// Structure struct Person { let name: String var age: Int func introduce() -> String { return "Hi, I'm \(name) and I'm \(age) years old." } } // Class class ViewController: UIViewController { @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() label.text = "Welcome to Swift!" } @IBAction func buttonTapped(_ sender: UIButton) { print("Button was tapped!") } }

SwiftUI Basics

import SwiftUI struct ContentView: View { @State private var name = "" var body: some View { VStack { Text("Hello, SwiftUI!") .font(.largeTitle) .foregroundColor(.blue) TextField("Enter your name", text: $name) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding() Button("Tap Me") { print("Hello, \(name)") } .buttonStyle(.borderedProminent) } .padding() } }

Common iOS Patterns

Delegate Pattern

protocol DataDelegate: AnyObject { func didReceiveData(_ data: String) } class DataManager { weak var delegate: DataDelegate? func fetchData() { // Simulate data fetching delegate?.didReceiveData("Sample data") } }

Networking with URLSession

func fetchData() async throws -> Data { let url = URL(string: "https://api.example.com/data")! let (data, _) = try await URLSession.shared.data(from: url) return data } // Usage Task { do { let data = try await fetchData() // Process data } catch { print("Error: \(error)") } }