Operators are special symbols or keywords that perform operations on one, two, or three operands.
You use operators to perform calculations, check conditions, assign values, and more.
Swift supports the standard C operators and improves upon them to eliminate common coding errors.
Arithmetic operators are used to perform common mathematical operations.
+ (Addition)- (Subtraction)* (Multiplication)/ (Division)% (Remainder / Modulo)let a = 10 let b = 3 print(a + b) // Outputs 13 print(a % b) // Outputs 1 (Remainder of 10 divided by 3)
The basic assignment operator is =, which assigns the value on the right to the variable on the left.
Swift also provides compound assignment operators that combine assignment with another operation.
+= (Add and assign)-= (Subtract and assign)*= (Multiply and assign)/= (Divide and assign)var score = 10 score += 5 // Equivalent to: score = score + 5 print(score) // Outputs 15
Comparison operators are used to compare two values. They always evaluate to a boolean value (true or false).
== (Equal to)!= (Not equal to)> (Greater than)< (Less than)>= (Greater than or equal to)<= (Less than or equal to)let x = 5 let y = 10 print(x == y) // Outputs false print(x < y) // Outputs true
Logical operators modify or combine boolean logic values.
&& (Logical AND): True if both conditions are true.|| (Logical OR): True if at least one condition is true.! (Logical NOT): Reverses the boolean value.let isAdult = true let hasTicket = false print(isAdult && hasTicket) // Outputs false print(!isAdult) // Outputs false
What does the `%` operator do in Swift?