Installation, Tools and First Program
2.1 Installing Swift
macOS: install Xcode from the App Store (it includes the Swift compiler, SwiftUI previews, Instruments, and simulators). xcode-select --install installs the command-line tools.
Linux: install with swiftly (the official toolchain manager), or download from swift.org/install:
Windows: the swift.org installer (winget install Swift.Toolchain) plus Visual Studio build tools.
Editors: Xcode, VS Code + the official Swift extension (SourceKit-LSP), Neovim/Emacs with SourceKit-LSP, JetBrains (Fleet/AppCode legacy).
curl -O https://download.swift.org/swiftly/linux/swiftly-$(uname -m).tar.gz
tar zxf swiftly-*.tar.gz && ./swiftly init
swiftly install latest
swift --version2.2 Ways to Run Swift
Playgrounds (Xcode or the Swift Playgrounds app) give immediate, live results. They're great for learning.
swift repl # interactive REPL (or just `swift`)
swift hello.swift # run a script directly
swiftc hello.swift -o hello # compile to an executable
./hello
swift package init --type executable --name MyTool # SwiftPM project
swift run
swift build -c release
swift test2.3 Hello, World
No main function needed: top-level code in main.swift (or a file with @main) is the entry point. No semicolons are required.
// main.swift
print("Hello, World!")
let name = "Swift"
print("Hello, \(name)!") // string interpolation
print("What's your name?", terminator: " ")
if let input = readLine() { // readLine returns String? (optional)
print("Nice to meet you, \(input)!")
}2.4 Comments and Documentation Comments
// Single-line comment
/* Multi-line comment
/* can be nested */ */
/// Calculates the area of a circle.
/// - Parameter radius: The circle's radius.
/// - Returns: The area.
func area(radius: Double) -> Double { .pi * radius * radius }