Short answer

Twelve basics come first when you learn Swift: let and var, the main types, if, switch, loops, functions, classes, structs, initializers, optionals, arrays and dictionaries. All twelve fit in one file that compiles and runs, in a playground or with swift basics.swift. The 2018 version of this list had snippets that don't compile, such as } other { and Print, and an initializer whose as! casts crash when a server sends a number where text was expected.

SWIFT TIPS · SWIFT LANGUAGE · BEGINNERS

First posted on September 25, 2018 for Swift 4.2, as "Swift 4 - Basic You Must Know to Learn Swift". Rewritten on November 18, 2026. The program below was compiled in Swift 6 mode and run on a Mac with Swift 6.2.3 (Xcode 26.2) on macOS 26.0.1, and the 2018 snippets were type-checked with the same compiler.

In 2018 I wrote a list of twelve basics for people starting Swift, each with a short explanation and an example: variables, data types, if, switch, loops, functions, classes, structs, initializers, optionals, arrays and dictionaries. Part of the text was in Indonesian, part in English. Several examples had words in the wrong order or the wrong case, such as ExampleVC class: UIViewController, value switch { and Print, so copying them into Xcode gave errors.

A beginner can't tell a typo from a rule, so this rewrite keeps the same twelve topics and puts them in one program that I compiled and ran. Every line of output below comes from it.

The whole program

// Swift basics in one file. Paste it into a playground, or run it with `swift basics.swift`.

// 1. Constants and variables
let greeting = "Hello"            // let: can't be changed after it's set
var name = "Budi"                 // var: can be changed
name = "Nisa"
print("1.", greeting, name)

// 2. Basic types (Swift infers them, or you can write them)
let age: Int = 20
let price: Double = 12_500.75     // 64-bit; the default for decimal numbers
let ratio: Float = 0.5            // 32-bit; use when an API asks for Float
let isMember: Bool = true
let initial: Character = "N"
print("2.", age, price, ratio, isMember, initial)
print("2. Float vs Double:", Float(2.3456789123), Double(2.3456789123))

// 3. if / else if / else
let score = 72
if score >= 80 {
    print("3. Great")
} else if score >= 60 {
    print("3. Passed")
} else {
    print("3. Try again")
}

// 4. switch: must cover every case; no fallthrough by default
let statusCode = 404
switch statusCode {
case 200..<300: print("4. Success")
case 401, 403:  print("4. Not allowed")
case 404:       print("4. Not found")
default:        print("4. Something else")
}

// 5. Loops
let names = ["Budi", "Nisa", "Brian"]
for name in names { print("5. Hello, \(name)!") }
for (index, name) in names.enumerated() where index > 0 { print("5. #\(index) \(name)") }
var countdown = 3
while countdown > 0 { print("5. \(countdown)"); countdown -= 1 }

// 6. Functions: labels, default values, return values
func total(of prices: [Double], discount: Double = 0) -> Double {
    prices.reduce(0, +) * (1 - discount)
}
print("6.", total(of: [10, 20, 30]), total(of: [10, 20, 30], discount: 0.1))

// 7. Classes: reference types (two names, one object)
final class Account {
    var balance: Int
    init(balance: Int) { self.balance = balance }
}
let a = Account(balance: 100)
let b = a
b.balance = 50
print("7. a.balance =", a.balance)     // 50: a and b are the same object

// 8. Structs: value types (each copy is separate)
struct Point { var x: Int; var y: Int }
let p1 = Point(x: 1, y: 2)            // memberwise initializer for free
var p2 = p1
p2.x = 10
print("8. p1.x =", p1.x, "p2.x =", p2.x)

// 9. Initializers: a failable init returns nil instead of crashing on bad data
struct Item {
    let id: String
    let value: String
    init?(dict: [String: Any]) {
        guard let id = dict["id"] as? String, let value = dict["value"] as? String else { return nil }
        self.id = id
        self.value = value
    }
}
print("9.", Item(dict: ["id": "1", "value": "Car"])?.value ?? "nil", Item(dict: ["id": 1])?.value ?? "nil")

// 10. Optionals: a value that may be missing
let input = "42a"
let number: Int? = Int(input)                 // nil: "42a" isn't a number
print("10.", number ?? 0)                     // ?? gives a default
if let number { print("10. got", number) } else { print("10. not a number") }
guard let parsed = Int("7") else { fatalError("unreachable in this example") }
print("10. parsed", parsed)

// 11. Arrays: ordered, one type
var words = ["Boat", "Fruit", "Car"]
words.append("Bike")
print("11.", words.count, words.first ?? "-", words.sorted())
print("11. index 10 exists?", words.indices.contains(10))

// 12. Dictionaries: key to value, lookups return an optional
var responseMessages = [200: "OK", 403: "Access forbidden", 404: "File not found"]
responseMessages[500] = "Internal server error"
print("12.", responseMessages[404] ?? "unknown", responseMessages[418] ?? "unknown")
for code in responseMessages.keys.sorted() { print("12.", code, responseMessages[code]!) }

What it printed

1. Hello Nisa
2. 20 12500.75 0.5 true N
2. Float vs Double: 2.3456788 2.3456789123
3. Passed
4. Not found
5. Hello, Budi!
5. Hello, Nisa!
5. Hello, Brian!
5. #1 Nisa
5. #2 Brian
5. 3
5. 2
5. 1
6. 60.0 54.0
7. a.balance = 50
8. p1.x = 1 p2.x = 10
9. Car nil
10. 0
10. not a number
10. parsed 7
11. 4 Boat ["Bike", "Boat", "Car", "Fruit"]
11. index 10 exists? false
12. File not found unknown
12. 200 OK
12. 403 Access forbidden
12. 404 File not found
12. 500 Internal server error

What each part shows

  1. let and var. Use let unless the value really changes. If you declare a var and never change it, the compiler warns you and suggests let.
  2. Types. Swift works out the type from the value, or you can write it. Float printed 2.3456788 and Double printed 2.3456789123: a Float keeps about 7 significant digits and a Double about 15. Use Double unless an API asks for Float.
  3. if needs a real Bool; a number doesn't count as true. No parentheses are needed around the condition.
  4. switch must cover every possible value, which is why there's a default. A case can be a range (200..<300) or a list (401, 403), and there's no fall-through, so no break is needed.
  5. Loops. for name in names goes through an array; enumerated() adds the index, and where skips items. The loops post linked below covers stride, zip and their traps.
  6. Functions have argument labels, like of:, that make calls read like a sentence, and default values, like discount = 0, that callers can leave out.
  7. Classes are shared. let b = a gives a second name to the same account, so changing b.balance changed a.balance to 50.
  8. Structs are copied. var p2 = p1 made a separate copy, so p1.x stayed 1. The 2018 post called a struct "a mini version of the class"; the real difference is this copy-versus-shared behavior. Most model types in Swift are structs, and a struct gets an initializer for its properties for free.
  9. A failable initializer, init?, returns nil when the data is wrong instead of crashing. For JSON from a server, Codable does this job for you and tells you which field was wrong.
  10. Optionals are values that may be missing. Int("42a") is nil because "42a" isn't a number. ?? gives a default, if let runs code only when there's a value, and guard let leaves early when there isn't.
  11. Arrays keep order and one type. first is optional because the array may be empty, and indices.contains(10) checks an index before you use it; reading past the end crashes.
  12. Dictionaries map keys to values. A lookup returns an optional, because the key may not be there (418 wasn't). The keys have no fixed order, so the loop sorts them to print the same way every time. The ! in that loop is safe only because each key came from the dictionary itself.

What didn't compile in 2018

The 2018 if/else example and print call, type-checked:
  line 5:2: error: consecutive statements on a line must be separated by ';'
  line 5:3: error: cannot find 'other' in scope
  line 8:1: error: cannot find 'Print' in scope
The 2018 string example with curly quotes, type-checked:
  line 1:26: error: unicode curly quote found, replace with '"'
  • } other { should be } else {. Swift has no other keyword.
  • Print should be print. Swift names are case-sensitive.
  • Curly quotes like the ones in the 2018 String = “ Hello ” line aren't string quotes in Swift; only the straight " is. They usually come from pasting code through a word processor or a blog editor.

The post also called String! "unwrapping". String! is an implicitly unwrapped optional: it can still be nil, and Swift unwraps it for you each time you use it, which crashes if it is nil. Use String? and unwrap it on purpose.

The initializer that crashed

The 2018 initializers section showed a struct built from a dictionary with as! String for each field. I gave it an id that arrived as a number, which happens when a server changes a field's type:

Server sent id as a number: ["id": 7, "value": "Car"]
Could not cast value of type 'Swift.Int' to 'Swift.String'.

The cast failed and the program stopped. Section 9's failable version returns nil for the same input, and Codable throws an error you can catch and report.

Where to go next

  • Paste the program into an Xcode playground (File, New, Playground) and change one value at a time.
  • Read "The Basics" in the Swift book, then "Structures and Classes".
  • When you hit "Unexpectedly found nil while unwrapping an Optional value", the post linked below shows where it comes from and how to fix it.

What the 2018 version said

The post's cover image showed the words "Learn Swift 4.2" over a screenshot of Xcode:

The words Learn Swift 4.2 over a screenshot of Swift code in Xcode

It ended with two references, the Swift book and Apple's Swift documentation, which are still the right places to read next; both are in the sources.

Sources