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.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *