Category: 01. Basic

https://cdn3d.iconscout.com/3d/premium/thumb/book-3d-icon-png-download-8786672.png

  • Swift Multiple Variables

    Swift Multiple Variables

    Declare multiple variables or constants on one line when they share a type.


    Multiple Variables Declared

    Declaring multiple variables or constants on one line is only recommended if it stays easy to read.

    Example

    var x = 1, y = 2, z = 3
    let a = 10, b = 20
    print(x, y, z, a, b)

    This example declares multiple variables and constants on one line.



    With Type Annotations

    Use explicit types when inference could be ambiguous or to document intent.

    Example

    var i: Int = 1, j: Int = 2
    let firstName: String = "Robin", lastName: String = "Refsnes"
    print(i + j, firstName, lastName)

    This example declares multiple variables and constants on one line.

  • Swift Print Variables

    Swift Print Variables

    Print values with concatenation or string interpolation.

    Use \(value) to insert values. You can set a separator and a terminator.


    Concatenation and Interpolation

    Use concatenation to combine strings and interpolate to embed values inside strings.

    Example

    let first = "Hello"
    let second = "Swift"
    // Concatenation
    print(first + ", " + second)
    // Interpolation
    print("\(first), \(second)")
    
    let a = 2, b = 3
    print("a = \(a), b = \(b), sum = \(a + b)")
    

    This example shows concatenation and interpolation.



    Custom Separator and Terminator

    Set a separator between items and a terminator at the end.

    Example

    let a = 1, b = 2, c = 3
    print(a, b, c, separator: ", ", terminator: "; ")
    print("done")  // prints on the same line after a semicolon

    This example sets a comma-space separator and a semicolon terminator.

  • Swift Variables

    Swift Variables

    Declare constants with let, variables with var, and use type inference or annotations as needed.


    Constants and Variables

    Declare constants with let and variables with var.

    Constants cannot be reassigned.

    Example

    let constant = 10
    var counter = 0
    counter += 1
    // constant = 12 // Error if uncommented
    print(constant, counter)

    This example shows that var can change while let cannot.


    Swift Type Inference

    Swift infers types automatically when possible, but you can also use annotations for clarity.

    Example

    let x = 10
    let y: Int = 20
    print(x, y)

    This example shows that Swift infers types automatically when possible, but you can also use annotations for clarity.

    Swift Data Types will be covered in more detail in the Swift Data Types chapter.



    Optionals

    Use ? to declare values that may be nil.

    Example

    var nickname: String? = nil
    nickname = "KJ"
    print(nickname ?? "none")

    This example shows an optional that may be nil.

  • Swift Comments

    Swift Comments

    Use comments to explain code.

    Swift supports single-line, multi-line (nestable), and documentation comments.


    Single-line and Multi-line

    Use // for single-line comments and /* ... */ for multi-line comments.

    Example

    // This is a single-line comment
    print("Hello")
    
    /* This is a
       multi-line comment */
    print("Swift")
    
    /* Nested comments are allowed:
      /* inner */
    */
    

    This example shows single- and multi-line comments.



    Documentation Comments

    Use /// before declarations to generate documentation, e.g. for functions, types, and properties.

    Documentation comments can include parameters, return values, and more.

    They differ from regular comments in that they are processed by the compiler and can be used to generate documentation.

    Example

    /// Returns the sum of two integers.
    /// - Parameters: a, b
    func add(_ a: Int, _ b: Int) -> Int { a + b }
    print(add(2, 3))
    

    This example uses triple-slash comments to document a function.

  • Swift Number Output

    Swift Number Output

    Print numeric values with print() and format using interpolation or format styles.


    Printing Numbers

    Print values directly or embed them using string interpolation with \(value).

    Example

    let a = 7, b = 3
    print(a, b)                 // space-separated by default
    print("a=\(a), b=\(b)")     // interpolation
    print("sum = \(a + b)")     // inline math
    

    This example prints numbers directly and via string interpolation, including inline addition.



    Math Functions

    Common functions like absmin, and max help compute numeric results.

    • abs(x) returns the absolute value of x.
    • min(x, y) returns the smaller of x and y.
    • max(x, y) returns the larger of x and y.

    Example

    let x = -7
    print(abs(x))          // 7
    print(min(3, 8))       // 3
    print(max(3, 8))       // 8

    This example shows absolute value, minimum, and maximum functions.

  • Swift Text Output

    Use print() to write text and values to output.

    Use string interpolation to combine values.


    Print Text

    Use print() to write text.

    Interpolate values with \(expr).

    Example

    print("Hello, Swift!")
    let name = "Kai"
    print("Hello, \(name)!")
    
    let a = 2, b = 3
    print("Total: \(a + b)")

    This example prints text and uses string interpolation to include values.



    Print Without Newline

    Use the terminator parameter to avoid a trailing newline.

    Example

    for n in 1...3 {
      print(n, terminator: " ") // prints on one line
    }
    print("done")

    This example prints numbers on a single line by setting terminator to a space, then prints done on the next line.

  • Swift Statements

    Swift Statements

    Swift code is built from statements such as declarations, expressions, and control flow (if, switch, loops).


    Expression & Declaration Statements

    Declarations introduce names (like variables and constants).

    Expression statements evaluate an expression, such as a function call.

    Example

    let x = 2  // declaration
    print(x)    // expression statement
  • Swift Syntax

    Learn Swift basics: variables, types, string interpolation, and simple functions.


    Basics

    Lets look at some basic Swift syntax:

    • Constants/variables: Use let (constant) and var (variable).
    • Types: Common types include IntDoubleBoolString.
    • Type inference: The compiler infers types from initial values.

    Example

    let greeting = "Hello"
    var name = "Swift"
    print(greeting + ", " + name)
    
    let pi: Double = 3.14159
    var count: Int = 3
    print("pi = \(pi), count = \(count)")

    Note: Unlike some other languages, in Swift let is used for constants and var for variables.

    Example explained

    • let creates an immutable constant; var creates a mutable variable.
    • Type annotation is optional; here we annotate Double and Int.
    • String interpolation\(expr) inserts values into strings.

    String Interpolation

    String interpolation is a way to embed expressions inside string literals for formatting.

    In swift string interpolation is done using \(expr).

    The most common and simple way to use string interpolation is to embed variable names inside string literals.

    Example

    let greeting = "Hello"
    var name = "Swift"
    print("\(greeting), \(name)!")

  • Swift Get Started

    Install the Swift toolchain and run your first “Hello, Swift!” program from the terminal or Xcode.


    Install Swift

    Swift can be installed on macOS, Windows, and Linux.

    • macOS (Xcode): Install Xcode from the App Store. Xcode includes the Swift compiler, SDKs, and tools.
    • macOS (Command line): Install the Swift toolchain, then run swift --version.
    • Windows/Linux: Install the platform toolchain from swift.org/install and ensure swift is on your PATH.

    Check install: Run swift --version in a terminal.

    You should see the Swift version and target.


    Hello World

    Swift can be run from the terminal or Xcode.

    Syntax: print("Hello, Swift!"); run with swift main.swift (or your toolchain’s run command).

    Example

    main.swift

    print("Hello, Swift!")

    Example explained

    • main.swift: A Swift file; the top-level print executes when run.
    • print: Writes text to standard output. Strings use double quotes.
  • Swift Introduction

    Swift is a modern, fast, and safe language for building apps across Apple platforms and beyond.


    What is Swift?

    Swift is a modern, fast, and safe programming language created by Apple.

    Use it to build apps for iPhone, iPad, Mac, Apple Watch, and Apple TV.

    You can also run Swift on servers (Linux, Windows, macOS).

    Swift helps you write correct and efficient code with type inference, optionals, value types, and protocol-oriented programming.

    Example

    print("Hello, Swift!")

    Why Use Swift?

    Swift focuses on safety and speed.

    Features like optionals, value types, and generics help you avoid bugs and keep code clear.

    • Great for iPhone/iPad, Mac, Apple Watch, and Apple TV development
    • Open source and available on multiple platforms
    • Expressive syntax, optionals to model absence, and value types for predictable behavior
    • Vibrant ecosystem and first-class tooling in Xcode

    Swift History

    A brief timeline of important Swift releases and milestones.

    • 2014: Swift 1.0 announced at WWDC as a modern successor to Objective-C
    • 2015: Swift became open source at swift.org, with Linux support
    • 2019: Swift 5 introduced ABI stability on Apple platforms
    • 2021: Swift 5.5 added structured concurrency (async/awaitTaskactor)
    • Today: Used across iOS, macOS, and server-side Swift


    Mac and Xcode for iOS Development

    If your goal is to build and run iOS apps, you should use a Mac with Xcode.

    • Xcode includes iOS SDKs, simulators, Interface Builder, and signing tools.
    • You can learn Swift on Windows or Linux and in the browser, but building and running iOS apps requires a Mac.
    • To ship to TestFlight or the App Store, you need an Apple Developer account.