Swift: Swift Introduction
Last updated: 2026-08-26
Swift is a modern programming language created by Apple. It combines the best of C and Objective-C while being safer, faster, and more readable. This lesson guides you through setting up your development environment from scratch and writing your very first line of Swift code.
1. What You'll Learn
- What Swift is and its core features
- Primary use cases for Swift
- How to install Xcode and Playgrounds
- How to write and run your first Swift program
- The basic structure of Swift code and the print function
2. A True Story: Switching Careers from Scratch
(1) The Pain Point: Want to Build Apps but Don't Know Where to Start
Alice was a market analyst with five years of experience. She wanted to transition into iOS development. After three days of searching online, she found plenty of resources but no clear starting point:
"Some people said learn Objective-C, others said Swift, and still others said to start with C. I downloaded Xcode—4.7GB—but when I opened it I had no idea where to click. The interface was way too complex."
Alice's dilemma is typical: information overload leading to decision paralysis.
(2) The Playgrounds Solution
A friend suggested she skip Xcode projects entirely and start with Swift Playgrounds instead—a lightweight, interactive Swift coding environment.
// Your first line of code in Swift Playgrounds
print("Hello, world!")
Playgrounds requires no project setup, no code signing, no Storyboard knowledge. Write a line of code and see the result instantly. Alice wrote her first program within 15 minutes.
(3) The Result: From Zero to One in 15 Minutes
| Dimension | Before | After |
|---|---|---|
| Mental barrier | "I can't learn programming" | "Writing code is actually simple" |
| Setup time | 3 days of indecision | 10 minutes to download Playgrounds |
| First program | Never wrote one | Hello World in 15 minutes |
| Confidence level | 0/10 | 7/10 |
3. What Is Swift
Swift is a modern programming language introduced by Apple at WWDC 2014 for building iOS, macOS, watchOS, and tvOS applications. It draws on excellent design concepts from multiple languages.
graph LR
A[Swift] --> B[Safe]
A --> C[Fast]
A --> D[Modern]
A --> E[Open Source]
B --> B1[Optionals eliminate null crashes]
B --> B2[Type safety prevents type errors]
C --> C1[LLVM compilation optimization]
C --> C2[Performance on par with C/Obj-C]
D --> D1[Closures/Generics/Pattern Matching]
D --> D2[Concise syntax, highly readable]
E --> E1[Open source on GitHub]
E --> E2[Runs on Linux too]
(1) Key Features of Swift
| Feature | Description | vs Objective-C |
|---|---|---|
| Type Safety | Checks type errors at compile time | Obj-C can pass id arbitrarily |
| Optionals | Use ? and ! to explicitly mark null values |
Obj-C's nil can send messages to any object |
| Automatic Memory Mgmt | ARC manages reference counts automatically | Obj-C requires manual retain/release |
| Closures | Functions are first-class citizens with closure expressions | Obj-C block syntax is cumbersome |
| Generics | Type parameterization for writing generic code | Obj-C does not support generics |
| Protocol Extensions | Protocols can have default implementations | Obj-C protocols can only declare |
| Open Source | Cross-platform with Linux support | Obj-C is not open source |
(2) What Can Swift Be Used For
| Domain | Framework/Tool | Description |
|---|---|---|
| iOS Apps | UIKit / SwiftUI | iPhone and iPad application development |
| macOS Apps | AppKit / SwiftUI | Mac desktop application development |
| watchOS | WatchKit | Apple Watch applications |
| tvOS | tvOS SDK | Apple TV applications |
| Server-side | Vapor / Kitura | Building backend APIs with Swift |
| Scripting | Swift Script | Replacing Shell/Python for daily tools |
▶ Example: Experience Swift with Playgrounds
// ============================================
// Experience Swift interactively in Playgrounds
// No Xcode project needed — just open and code
// ============================================
let greeting = "Hello, Swift!"
print(greeting)
// Display calculation results directly
let result = 42 + 10
print("42 + 10 = \(result)")
Output:
TEXT 📖 Display onlyHello, Swift! 42 + 10 = 52
4. Setting Up Your Development Environment
(1) Choosing Your Setup
| Option | Best For | Installation | Size |
|---|---|---|---|
| Xcode | Professional iOS/macOS development | Download from Mac App Store | ~7GB |
| Playgrounds | Beginners learning Swift syntax | Mac App Store / iPad App Store | ~150MB |
| Swift on Linux | Server-side development / cross-platform | apt install swift |
~500MB |
| Online Playground | Quick testing, no installation | Browser-based | 0 |
(2) Installing Playgrounds (Recommended for Beginners)
If you have a Mac or iPad, the fastest way to get started is installing Swift Playgrounds:
- Open the Mac App Store (or iPad App Store)
- Search for "Swift Playgrounds"
- Click "Get" to install
After installation, just open it and start coding. No Apple Developer account needed, no certificate signing required.
(3) Installing Xcode (For Advanced Development)
Xcode is Apple's official integrated development environment, including the complete iOS development toolchain:
# Two ways to install Xcode
# 1. Search "Xcode" in Mac App Store and download (recommended)
# 2. Download the .xip package from the Apple Developer website
▶ Example: Creating a Playground in Xcode
// ============================================
// Create a Playground file in Xcode
// File → New → Playground → Blank
// ============================================
import UIKit
var number = 42
number += 10
// The Playground sidebar shows variable values in real time
print(number)
Output:
TEXT 📖 Display only52
5. The Structure of Your First Swift Program
Every Swift program starts executing from the entry file. In Playgrounds, code executes line by line from top to bottom.
(1) Basic Structure
graph TB
A[Swift Source File .swift] --> B[Import Frameworks]
A --> C[Variable/Constant Declarations]
A --> D[Function Definitions]
A --> E[Expressions and Statements]
B --> F["import Foundation"]
B --> G["import UIKit"]
C --> H["let name = \"Alice\""]
C --> I["var age = 28"]
D --> J["func sayHello() { ... }"]
E --> K["print(\"Hello\")"]
(2) Understanding the print Function
print is Swift's most commonly used output function for displaying content in the console.
// ============================================
// Basic usage of the print function
// ============================================
// 1. Output a string
print("Hello, Swift!")
// 2. Output multiple values (auto space-separated)
print("Hello", "Swift", "World")
// 3. String interpolation
let name = "Alice"
print("My name is \(name)")
// 4. Specify separator and terminator
print("One", "Two", "Three", separator: ", ", terminator: ".\n")
Output:
TEXT 📖 Display onlyHello, Swift! Hello Swift World My name is Alice One, Two, Three.
▶ Example: A Complete Swift Program Structure
// ============================================
// Complete Swift program: Personal Info Card
// Demonstrates import, constants, variables, print
// ============================================
import Foundation
// Constants (immutable)
let appName = "Swift Starter"
let author = "Alice"
// Variables (mutable)
var year = 2026
var version = 1.0
// Output
print("Welcome to \(appName)")
print("Author: \(author), Year: \(year)")
print("Version: v\(version)")
// Update version number
version = 1.1
year = 2026
print("Updated: v\(version) (\(year))")
Output:
TEXT 📖 Display onlyWelcome to Swift Starter Author: Alice, Year: 2026 Version: v1.0 Updated: v1.1 (2026)
6. Full Example: Build a Simple Calculator in Playgrounds
// ============================================
// Full example: Playground Calculator
// Demonstrates basic arithmetic operations
// ============================================
import Foundation
// 1. Define inputs
let a = 25
let b = 7
// 2. Calculate
let sum = a + b
let difference = a - b
let product = a * b
let quotient = a / b
let remainder = a % b
// 3. Format and output results
print("a = \(a), b = \(b)")
print("=== Results ===")
print("Addition: \(a) + \(b) = \(sum)")
print("Subtraction: \(a) - \(b) = \(difference)")
print("Multiplication: \(a) × \(b) = \(product)")
print("Division: \(a) ÷ \(b) = \(quotient) remainder \(remainder)")
Output:
TEXT 📖 Display onlya = 25, b = 7 === Results === Addition: 25 + 7 = 32 Subtraction: 25 - 7 = 18 Multiplication: 25 × 7 = 175 Division: 25 ÷ 7 = 3 remainder 4
❓ FAQ
📖 Summary
- Swift is a modern programming language from Apple for building iOS/macOS/watchOS/tvOS applications
- Beginners should start with Playgrounds — fast to install, no configuration needed
- Swift's three main advantages: safe, fast, and modern
- Your first Swift program starts with
print("Hello, World!") - Playgrounds provides real-time feedback — see results instantly after writing each line of code
- This tutorial assumes zero prior experience, guiding you from beginner to building practical CLI tools over 28 lessons
📝 Exercises
-
Beginner: Install Swift Playgrounds (or open Xcode and create a Playground), then use the
printcommand to output your name and the current year. -
Intermediate: Modify the full calculator example from Section 6 by adding detailed multiplication demonstrations (at least 3 different sets of numbers) and use the
separatorparameter to beautify the output format. -
Challenge: Following the code style from Section 6, create a "unit converter" program that converts between Celsius and Fahrenheit (formula:
°F = °C × 9/5 + 32). Display results in both units.