Author: saqibkhan

  • Swift Operator Precedence

    Swift Operator Precedence

    Operator precedence determines evaluation order.

    Multiplication comes before addition; && before ||.

    Use parentheses to control order.


    Control order of evaluation with precedence

    Understand how operators are prioritized and add parentheses to make evaluation order explicit when needed.

    Example

    print(2 + 3 * 4)
    print((2 + 3) * 4)
    print(true || false && false)
    print((true || false) && false)

    This example shows how parentheses change the result.



    Boolean Precedence

    && is evaluated before ||. Use parentheses to clarify intention.

    Example

    let a = true
    let b = false
    let c = true
    
    print(a || b && c)         // true (&& before ||)
    print((a || b) && c)       // true
    print(a && b || c)         // true ((a && b) || c)
  • Swift Logical Operators

    Swift Logical Operators

    Combine booleans with && (AND), || (OR), and ! (NOT).


    Logical AND (&&)

    Both must be true for the result to be true.

    Example

    let isOwner = true
    let isAdmin = false
    print(isOwner && isAdmin)
    print(true && true)

    Logical OR (||)

    At least one true makes the result true.

    Example

    let a = true
    let b = false
    print(a || b)
    print(false || false)


    Logical NOT (!)

    Flip a boolean value: true becomes false and vice versa.

    Example

    let flag = false
    print(!flag)
    print(!true)

  • Swift Comparison Operators

    Swift Comparison Operators

    Use comparison operators to compare values: ==!=><>=<=.

    They return Bool.


    Compare Integers

    Use ==!=><>=, and <= to compare numeric values.

    The result is a Bool.

    Example

    let a = 5, b = 2
    print(a == b)
    print(a != b)
    print(a > b)
    print(a < b)
    print(a >= 5)

    This example prints the result of several comparisons.



    Compare Strings

    Strings compare lexicographically (dictionary order).

    Comparison is case-sensitive.

    Example

    print("apple" < "banana")  // true
    print("Swift" == "Swift")  // true
    print("cat" > "car")       // true

    This example compares strings using the same operators.

  • Swift Assignment Operators

    Swift Assignment Operators

    Use = to assign a value.

    Compound assignment operators like +=-=*= and /= update a variable in place.


    Compound Assignment

    Use compound operators like += and *= to update a variable in place.

    Example

    var total = 10
    total += 5
    print(total)
    total -= 3
    print(total)
    total *= 2
    print(total)
    total /= 4
    print(total)

    This example shows updating a variable with compound assignment operators.



    Append to String

    You can also use += with strings to append text to a mutable string variable.

    Example

    var s = "Hello"
    s += ", Swift"
    print(s)

    This example appends to a string in place with +=.

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