Operators
Arithmetic Operators
| Operator | Description | Example |
|---|---|---|
+ | Addition | a + b |
- | Subtraction (binary) | a - b |
- | Negation (unary) | -a |
* | Multiplication | a * b |
/ | Division | a / b |
^ | Power (exponentiation) | a ^ b |
% | Modulo (remainder) | a % b |
When both operands of / are Int, the result is an Int with the fractional part truncated. Use a Float operand to get a floating-point result.
var a = 7 / 2 // 3 (truncated)
var b = 7.0 / 2 // 3.5
var c = 7 / 2.0 // 3.5
Comparison Operators
All comparison operators produce a Bool result.
| Operator | Description | Example |
|---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
< | Less than | a < b |
> | Greater than | a > b |
<= | Less than or equal to | a <= b |
>= | Greater than or equal | a >= b |
Identity Operator
The identity operator checks whether two variables refer to the same class instance.
| Operator | Description | Example |
|---|---|---|
=== | Same instance | a === b |
Unlike ==, which compares values, === only applies to class instances. Two distinct instances with identical property values are not identical.
var a = Point(x: 1.0, y: 2.0)
var b = a
var c = Point(x: 1.0, y: 2.0)
print("\{a === b}") // Prints "true" — same instance
print("\{a === c}") // Prints "false" — different instances, equal values
Logical Operators
All logical operators work with Bool values and produce a Bool result.
| Operator | Description | Example |
|---|---|---|
not | Logical negation (unary) | not condition |
and | Logical conjunction | a and b |
or | Logical disjunction | a or b |
and and or use short-circuit evaluation: the right operand is only evaluated if the left operand does not already determine the result.
Bitwise Operators
Bitwise operators work on the individual bits of integer values.
| Operator | Description | Example |
|---|---|---|
& | Bitwise AND | a & b |
| | Bitwise OR | a | b |
~ | Bitwise XOR (binary) | a ~ b |
~ | Bitwise NOT / complement (unary) | ~a |
<< | Left shift | a << b |
>> | Right shift | a >> b |
var flags = 10 // 0b1010
var mask = 12 // 0b1100
print("\{flags & mask}") // Prints "8" (0b1000)
print("\{flags | mask}") // Prints "14" (0b1110)
print("\{flags ~ mask}") // Prints "6" (0b0110)
print("\{~flags}") // Prints "-11"
print("\{flags << 1}") // Prints "20" (0b10100)
print("\{flags >> 1}") // Prints "5" (0b0101)
Ternary Conditional Operator
The ternary operator evaluates a Bool condition and produces one of two values. Both branches must produce a compatible type.
condition ? value_if_true : value_if_false
var score = 150
var label = score > 100 ? "Won" : "Lost"
The result may also be an optional:
var condition: Bool = true
var opt: String? = condition ? "value" : nil
Assignment Operator
The = operator assigns a value to an existing variable. It does not itself produce a value.
var x = 10
x = 20