Author: saqibkhan

  • Swift Data Types

    Swift Data Types

    Swift has built-in types like IntDoubleBool and String.

    Swift uses type inference to deduce the type from the value.


    Basic Types

    Declare constants with let and variables with var.

    Swift infers the type from the initial value.

    Example

    let anInt = 42           // Int
    let aDouble = 3.14       // Double
    let isSwiftFun = true    // Bool
    let greeting = "Hello"    // String
    print(aDouble)
    print(isSwiftFun)
    print(greeting)

    This example declares common Swift types and prints them.



    Type Inference vs Annotation

    Swift usually infers the type from the initial value, but you can add a type for clarity.

    Example

    let inferred = 10          // Int (inferred)
    let annotated: Double = 3  // Double (explicit)
    print(type(of: inferred), type(of: annotated))

    This example contrasts inferred vs. explicit types.

  • Swift Variables in Real-Life

    Swift Variables in Real-Life

    Use variables to track values like counters, flags, and user input.


    Example: Counter

    Use a variable to track a counter and print it as it changes.

    Example

    var count = 0
    count += 1
    print("Count: \(count)")
    


    Example: Greeting

    Store a value in a variable and use interpolation to print it.

    Example

    var name = "Kai"
    print("Hello, \(name)!")
    name = "Elisabeth"
    print("Hello, \(name)!")

    This example updates a variable and prints the new greeting.

  • Swift Constants

    Swift Constants

    Use let to declare constants that don’t change.


    Declare Constants

    Use let to bind a value once so it cannot be reassigned later.

    Example

    let pi = 3.14159
    let maxCount = 100
    // pi = 4.0 // Error: cannot assign to value: 'pi' is a 'let' constant


    Constants and Collections

    If an array is bound with let, you can’t mutate (change) it.

    Example

    var nums = [1, 2]
    nums.append(3)       // OK: nums is var
    print(nums)
    
    let fixed = [1, 2]
    // fixed.append(3)  // Error if uncommented: cannot use mutating member on immutable value

    Binding with let is immutable, so you can’t mutate it.


  • Swift Identifiers

    Swift Identifiers

    Identifiers name variables, constants, types, functions, etc.


    Rules for Identifiers

    Identifiers must:

    • Start with a letter or underscore.
    • May include numbers after the first character.
    • Avoid keywords unless escaped with backticks.

    They can contain Unicode and must not start with a number.

    Example

    let name = "Swift"
    let π = 3.14
    let _hidden = true
    


    Escaping Keywords and Unicode

    Escape keywords with backticks when needed, and remember identifiers can include Unicode characters.

    Example

    let switch = "ok"   // escape a keyword using backticks
    let 🐶 = "dog"          // Unicode identifier
    print(switch, 🐶)

    Use backticks to escape reserved words in identifiers, and remember Swift identifiers can include Unicode characters.

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