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


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.

SWIFT
// 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.

100%
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

SWIFT
// ============================================
// 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 only
Hello, 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

If you have a Mac or iPad, the fastest way to get started is installing Swift Playgrounds:

  1. Open the Mac App Store (or iPad App Store)
  2. Search for "Swift Playgrounds"
  3. 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:

BASH
# 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
⚠️ Note: Xcode is approximately 7GB and takes 15-30 minutes to install (depending on your internet speed). If you just want to learn Swift syntax, start with Playgrounds first.

▶ Example: Creating a Playground in Xcode

SWIFT
// ============================================
// 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 only
52

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

100%
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.

SWIFT
// ============================================
// 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 only
Hello, Swift!
Hello Swift World
My name is Alice
One, Two, Three.

▶ Example: A Complete Swift Program Structure

SWIFT
// ============================================
// 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 only
Welcome to Swift Starter
Author: Alice, Year: 2026
Version: v1.0
Updated: v1.1 (2026)

6. Full Example: Build a Simple Calculator in Playgrounds

SWIFT
// ============================================
// 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 only
a = 25, b = 7
=== Results ===
Addition: 25 + 7 = 32
Subtraction: 25 - 7 = 18
Multiplication: 25 × 7 = 175
Division: 25 ÷ 7 = 3 remainder 4

❓ FAQ

Q Do I need to learn another language before Swift?
A No. Swift is designed for beginners, and starting from scratch is entirely feasible. This tutorial assumes no prior programming experience.
Q Can I learn Swift without a Mac?
A Yes. You can use the web-based Swift Playgrounds, online editors like SwiftFiddle, or install the Swift toolchain on Linux. However, publishing apps to the App Store ultimately requires a Mac.
Q What's the relationship between Swift and SwiftUI?
A Swift is the programming language; SwiftUI is a UI framework built on top of Swift. Learn Swift fundamentals first (this tutorial), then tackle SwiftUI for building interfaces. It's like learning grammar before writing.
Q Xcode is huge. Can I complete this entire tutorial with only Playgrounds?
A Absolutely. Every code example in this tutorial runs in Playgrounds. You can get through all 28 lessons before even thinking about installing Xcode.
Q Can Swift run on Windows?
A Windows is not officially supported. However, you can use online editors like SwiftFiddle or install WSL to run Swift on Ubuntu.

📖 Summary


📝 Exercises

  1. Beginner: Install Swift Playgrounds (or open Xcode and create a Playground), then use the print command to output your name and the current year.

  2. Intermediate: Modify the full calculator example from Section 6 by adding detailed multiplication demonstrations (at least 3 different sets of numbers) and use the separator parameter to beautify the output format.

  3. 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.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏