Category: 01. Basic

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

  • Swift Arithmetic Operators

    Swift Arithmetic Operators

    Use +-*, and / to add, subtract, multiply and divide.

    Integer division truncates toward zero.


    Examples

    These examples show addition, subtraction, multiplication and integer division.

    Example

    let a = 7, b = 3
    print(a - b)
    print(a * b)
    print(a / b)        // integer division

    This example demonstrates arithmetic with integers.



    Remainder Operator

    The remainder operator % gives the leftover after integer division.

    Example

    print(7 % 3)   // 1
    print(8 % 2)   // 0
    print(10 % 6)  // 4

    Use % to check divisibility or cycle through a fixed range.

  • Swift Operators

    Swift Operators

    Operators perform operations on values.

    Common groups are arithmeticassignmentcomparison and logical operators.

    Swift also has well-defined precedence.


    Operator families at a glance

    Explore arithmetic, assignment, comparison, and logical operators, and how precedence affects evaluation order.

    Example

    let a = 5, b = 2
    // Arithmetic
    print(a + b)
    // Comparison
    print(a > b)
    // Logical
    let t = true, f = false
    print(t && !f)

    This example shows arithmetic (+), comparison (>) and logical (&&!) operators.



    Unary and Ternary

    Unary operators act on a single operand (like ! to negate a boolean).

    The ternary conditional operator condition ? a : b chooses between two values.

    Example

    let flag = false
    print(!flag)              // unary NOT
    let score = 85
    let label = (score >= 90) ? "A" : "Not A"
    print(label)

    This example flips a boolean with unary ! and uses the ternary operator to pick a string based on a condition.

  • Swift Type Casting

    Swift Type Casting

    Use asas?, and as! to convert between types, especially with protocols and Any.


    Upcasting and Downcasting

    Convert a value to a supertype (upcast) or attempt to convert back to a subtype using optional downcasting with as?.

    Example

    let items: [Any] = [1, "Swift"]
    for item in items {
      if let i = item as? Int {
    
    print("Int: \(i)")
    } else if let s = item as? String {
    print("String: \(s)")
    } }

    This example conditionally casts values from Any to their concrete types.



    Forced Downcast

    Use as! only when you are certain of the runtime type. If the cast fails, the program will crash.

    Example

    let value: Any = 42
    let i = value as! Int   // forced downcast
    print(i)

    Prefer optional casting (as?) when the type may vary, and unwrap safely.

  • Swift Characters

    Swift Characters

    Character is one user-visible character.

    Strings are collections of characters.


    Characters and String Length

    Use Character for single letters.

    Use String.count to get the number of characters.

    Example

    let ch: Character = "A"
    print(ch)
    let word = "Swift"
    print(word.count)

    This prints a character and a string length.


    Characters and String Conversion

    Convert between Character and String as needed.

    Example

    let ch: Character = "A"
    let s = String(ch)
    print(s)              // "A"


    Unicode and Grapheme Clusters

    Some characters use multiple Unicode scalars but still count as one character.

    Example

    let heart: Character = "❤️"
    print(heart)
    let flag: Character = "🇳🇴" // composed of two regional indicators
    print(flag)
    print("e\u{301}".count) // 1 (e + combining acute accent)
  • Swift Booleans

    Swift Booleans

    Bool represents logical true/false. Combine conditions with &&||, and negate with !.


    Boolean Logic

    Combine boolean values using logical AND (&&), OR (||), and negate with NOT (!).

    Example

    let a = true, b = false
    print(a && b)
    print(a || b)
    print(!a)

    This example shows logical AND, OR and NOT.



    Comparison Results

    Relational operators like >==, and != return Bool values that you can use in conditions.

    Example

    let a = 5, b = 3
    print(a > b)   // true
    print(a == b)  // false
    print(a != b)  // true

    Comparisons like >==, and != produce Bool values you can combine with logical operators.

  • Swift Numbers

    Swift Numbers

    Swift has integer types (like Int) and floating-point types (like Double).

    Use arithmetic operators to add, subtract, multiply and divide numbers.


    Arithmetic

    Use +-*, and / to perform numeric operations. Convert types when needed.

    Example

    let a = 5, b = 2
    print(a - b)
    print(a * b)
    print(Double(a) / Double(b))

    This example demonstrates basic arithmetic and integer-to-double conversion for division.



    Integer Division vs Remainder

    Integer division drops any fractional part, while % returns the remainder.

    Example

    let a = 7, b = 3
    print(a / b)  // 2 (integer division)
    print(a % b)  // 1 (remainder)

    This example shows how integer division truncates toward zero and how the remainder operator % returns the leftover.

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