SwSwift

Learn Swift – tutorial, cheatsheet & exercises

Swift is Apple's modern programming language for iOS, iPadOS, macOS, watchOS, tvOS, and visionOS. It is statically typed, compiles to fast machine code (LLVM), and puts great emphasis on safety: variables are always initialized, optionals make “no value” visible in the type system, arrays check their bounds, and memory is managed automatically via ARC, without a garbage collector.

The language is expressive and readable: type inference, closures, enums with values, protocols with default implementations, and a modern concurrency model (async/await, actors). With SwiftUI you describe user interfaces declaratively. Swift also runs on Linux, Windows, and on servers (Vapor), but it is above all the language of the Apple ecosystem.

iOS/iPadOSmacOSwatchOSServer

Hello World in Swift

print("Hello World!")

print outputs text: no main, no braces around the block, no semicolon. Run it with swift hallo.swift.

How to get started with Swift

The most convenient way to install Swift on a Mac is via Xcode (free in the Mac App Store). It includes the compiler, simulators for iPhone/iPad, interface tools, and playgrounds. If you only need the command-line tools: xcode-select --install. For Linux and Windows there are toolchains on swift.org.

swift --version

You can run single files directly as a script or compile them to a binary:

# run as a script (interpreted via JIT)
swift hallo.swift

# compile and run
swiftc hallo.swift -o hallo
./hallo

Playgrounds are great for learning and experimenting: in Xcode via *File > New > Playground* (or in the *Swift Playground* app on iPad and Mac). Every line shows its result immediately, without needing a whole project.

For larger programs and libraries you use the Swift Package Manager (SwiftPM). It is built into Swift and works without Xcode:

mkdir Hallo && cd Hallo
swift package init --type executable
swift run          # build and run
swift test         # run tests
TipIf you want to build an iPhone app, you create a new project in Xcode (*iOS > App*, interface: SwiftUI). The bundled simulator is enough for testing; for your own device a free Apple ID is sufficient.
TipThe language itself runs on Mac, Linux, and Windows. Frameworks such as SwiftUI, UIKit, and AppKit (examples with import SwiftUI), on the other hand, exist only on Apple platforms.

At a glance

First released2014
CreatorChris Lattner (Apple)
ParadigmMulti-paradigm (OOP, protocol-oriented, functional)
TypingStatic, strong
ExecutionCompiled to machine code (LLVM)
File extension.swift

Test & practice

Interactive quiz, timed exam with certificate, and exercises with an editor:

Swift compared

Hello World: Swift comparedVariables: Swift comparedConditionals: Swift comparedLoops: Swift comparedFunctions: Swift comparedLists and Arrays: Swift comparedDictionaries and Maps: Swift comparedClasses and Objects: Swift comparedError Handling: Swift comparedReading Files: Swift compared