Skip to content

Swift Basics

This guide introduces fundamental Swift concepts, focusing on data types, variables, constants, and basic syntax.

Fundamental Data Types

Swift provides several core data types:

  • Int: Whole numbers (e.g., 100, -50)
  • Double: 64-bit floating-point numbers (e.g., 2.71828)
  • Float: 32-bit floating-point numbers
  • Bool: true or false values
  • String: Text (e.g., "Welcome")
  • Collections: Array, Set, Dictionary

Note: Prefer Double for floating-point numbers unless Float is needed for specific cases (e.g., memory constraints). Use Int for general integer purposes.

Constants and Variables

  • Constants (let): Immutable values.
  • Variables (var): Mutable values.
swift
let maxScore = 100 // Constant
var currentScore = 0 // Variable
  • Declare multiple variables/constants in one line:
swift
var a = 1.0, b = 2.0, c = 3.0
  • Initialize constants later, ensuring a value before use:
swift
var mode = "test"
let maxPlayers: Int
if mode == "test" {
    maxPlayers = 50
} else {
    maxPlayers = 10
}

Type Annotations

Explicitly declare types using a colon (:):

swift
var greeting: String = "Welcome"
var height, width, depth: Double

Swift infers types from initial values, reducing the need for annotations:

swift
let answer = 42 // Inferred as Int
let euler = 2.71828 // Inferred as Double

Naming Rules

  • Names can include Unicode characters:
swift
let Σ = 1.414 // Square root of 2
let こんにちは = "Hello, world"
let 🦁 = "lion"
  • Cannot start with numbers, or include whitespace, mathematical symbols, or specific Unicode characters.
  • Cannot redeclare names or convert constants to variables.

Printing Values

Use print() with string interpolation:

swift
var userGreeting = "Welcome!"
print("Current greeting: \(userGreeting)")
// Prints: Current greeting: Welcome!

Comments

  • Single-line: // Single-line comment
  • Multi-line: /* Multi-line comment */
  • Nested multi-line comments:
swift
/* Main comment
    /* Nested comment */
End of main comment */

Semicolons

Semicolons (;) are optional unless multiple statements are on one line:

swift
let emoji = "😺"; print(emoji) // Prints 😺

Integers

  • Signed: Int8, Int16, Int32, Int64 (e.g., Int8: -128 to 127)
  • Unsigned: UInt8, UInt16, UInt32, UInt64 (e.g., UInt8: 0 to 255)
  • Use Int for general use, matching platform word size.
  • Check bounds:
swift
let min = UInt8.min // 0
let max = UInt8.max // 255

Numeric Literals

Integers:

  • Decimal: 25
  • Binary: 0b11001 (25)
  • Octal: 0o31 (25)
  • Hexadecimal: 0x19 (25)

Floating-point:

  • Decimal: 15.625, 1.5625e1 (1.5625 × 10¹)
  • Hexadecimal: 0xF.Ap0 (15.625)
  • Use underscores for readability:
swift
let largeNumber = 1_000_000
let preciseDouble = 123_456.789_012

Type Safety and Inference

Swift is type-safe, preventing type mismatches. Type inference deduces types:

swift
let constant = 2.71828 // Inferred as Double
let result = 2 + 0.71828 // Inferred as Double

Type Conversion

Explicit conversion is required:

swift
let thousand: UInt16 = 1_000
let ten: UInt8 = 10
let total = thousand + UInt16(ten) // 1010

For floating-point and integers:

swift
let whole = 5
let fraction = 0.859
let sum = Double(whole) + fraction // 5.859
let intSum = Int(sum) // 5 (truncates)

Type Aliases

Define alternative type names:

swift
typealias PixelValue = UInt8
var brightness = PixelValue.max // 255

Booleans

Bool is true or false:

swift
let isSunny = true
if isSunny {
    print("It's a sunny day!")
} else {
    print("It's cloudy.")
}
// Prints: It's a sunny day!

Tuples

Group values into a single compound value:

swift
let userStatus = (200, "Online") // Type: (Int, String)

Access elements:

  • By index: userStatus.0 (200)
  • By name: let response = (code: 200, message: "Success")
  • Decompose: let (code, message) = userStatus

Optionals

Handle absent values with nil:

swift
let input = "456"
let number: Int? = Int(input) // Optional Int
  • Check for nil:
swift
if number != nil {
    print("Valid number")
}
  • Optional Binding:
swift
if let value = number {
    print("Value is \(value)") // Value is 456
}
  • Nil-Coalescing Operator (??):
swift
let username: String? = nil
let displayName = username ?? "Guest"
print("Hello, \(displayName)!") // Hello, Guest!
  • Force Unwrapping (!): Use only if guaranteed non-nil:
swift
let value = number! // 456
  • Implicitly Unwrapped Optionals (Type!):
swift
let assumedName: String! = "User"
let name: String = assumedName // No unwrapping needed

Memory Safety

Swift ensures:

  • Initialized values before use.
  • Valid array index access.
  • Memory access within lifetime.
  • Safe concurrent memory access.

Unsafe APIs (e.g., "unsafe") require manual safety checks.

Error Handling

Manage errors with throws, try, do, catch:

swift
enum GameError: Error {
    case noPlayers
    case invalidMove(String)
}

func startGame() throws {
    throw GameError.invalidMove("Invalid position")
}

do {
    try startGame()
} catch GameError.noPlayers {
    print("Need players to start")
} catch GameError.invalidMove(let move) {
    print("Error: \(move)")
}
// Prints: Error: Invalid position

Assertions and Preconditions

  • Assertions: Debug-only checks:
swift
let level = -1
assert(level > 0, "Level must be positive") // Fails in debug
  • Preconditions: Checked in debug and production:
swift
precondition(index >= 0, "Index must be non-negative")
  • Fatal Errors: Always halt:
swift
fatalError("Feature not implemented")

Assertions and preconditions ensure valid program states, aiding debugging and reliability.

Released under the MIT License.