Skip to main content

Operators

Arithmetic Operators

OperatorDescriptionExample
+Additiona + b
-Subtraction (binary)a - b
-Negation (unary)-a
*Multiplicationa * b
/Divisiona / 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.

OperatorDescriptionExample
==Equal toa == b
!=Not equal toa != b
<Less thana < b
>Greater thana > b
<=Less than or equal toa <= b
>=Greater than or equala >= b

Identity Operator

The identity operator checks whether two variables refer to the same class instance.

OperatorDescriptionExample
===Same instancea === 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.

OperatorDescriptionExample
notLogical negation (unary)not condition
andLogical conjunctiona and b
orLogical disjunctiona 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.

OperatorDescriptionExample
&Bitwise ANDa & b
|Bitwise ORa | b
~Bitwise XOR (binary)a ~ b
~Bitwise NOT / complement (unary)~a
<<Left shifta << b
>>Right shifta >> 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