Skip to content

Advanced Operators ​

Implementation status: half-open ranges / optional chaining / force unwrap / nil coalescing / pattern matching / custom operators GA (operator func + three-back-end parity); bitwise operations / overflow behavior Implemented; custom prefix / postfix / infix Implemented; precedence / associativity declarations Implemented

An operator is a function with "special syntax". SYX is like Swift: built-in operators are part of the language surface (compiler hard-coded + Core Host bridge), and users may declare custom operators (infix / prefix / postfix) with precedence / associativity.

Built-in Operator Cheat Sheet ​

For the complete list, see Chapter 3, Basic Operators. This section adds the "advanced" subset:

Bitwise Operations (Integers) ​

OperatorMeaningType
&Bitwise ANDInteger
|Bitwise ORInteger
^Bitwise XORInteger
~Bitwise NOT (unary)Integer
<<Left shiftInteger
>>Right shift (arithmetic)Integer
swift
let a: Int = 0b1100                        // 12
let b: Int = 0b1010                        // 10
print(a & b)                                // 8  (0b1000)
print(a | b)                                // 14 (0b1110)
print(a ^ b)                                // 6  (0b0110)
print(~a)                                   // -13
print(a << 2)                               // 48
print(a >> 1)                               // 6

Precedence: bitwise operations come after comparison == and before logical &&. a == b & c means a == (b & c).

Custom Prefix / Postfix / Infix Operators ​

text
// Custom operator declarations (parser deep dig OUT this window; illustrative only)
prefix operator !
postfix operator **
infix operator |> { precedence: 50, associativity: left }

Precedence / Associativity ​

text
infix operator ^^ { precedence: 100, associativity: right }
func ^^&lt;T&gt;(a: T, b: T) -> T where T: Numeric { return a * a }
FieldValueMeaning
precedenceInteger (0–200)Higher binds tighter
associativityleft / right / noneSame-precedence combining direction
higherThan / lowerThanOperator nameRelative position

Predefined precedences (partial): * / % are 100; + - are 90; << >> are 80; < > and friends are 70; == != are 60; & is 50; ^ is 40; \| is 30; && is 20; || is 10.

Operator Functions and Protocol Constraints ​

text
infix operator <*> { precedence: 60 }
func <*> &lt;T: Numeric&gt;(a: Array&lt;T&gt;, b: Array&lt;T&gt;) -> Array&lt;T&gt; { … }
let r = [1, 2, 3] <*> [4, 5, 6]            // [4, 10, 18]

Status: operator func is GA (Phase 41+), with parity across the three back ends (VM / unified MIR / WASM).

Half-Open Ranges ​

swift
for i in 0..<10 {                           // [0, 10)
    print(i)
}

let r = 1..<10
print(r.contains(5))                        // true
print(r.contains(11))                       // false
print(r.contains(0))                        // true
FormStatusMeaning
a..<bImplementedHalf-open [a, b)
a...bPartially implementedClosed [a, b]
a..< / ..<bNot implementedOne-sided infinite

Optional Chaining ?. ​

swift
let maybe: String? = "hello"
let len = maybe?.count                    // Optional(5)
let bad = (nil as String?)?.count         // nil

Chains may be arbitrarily long:

swift
class A { let b: B? = B() }
class B { let c: C? = C() }
class C { let name: String = "x" }

let a: A? = A()
print(a?.b?.c?.name)                        // Optional("x")
print(a?.b?.c?.name?.count)                // Optional(1)

?. semantics: if any link in the chain is nil → the whole thing is nil.

Force Unwrap ! ​

swift
let present: String? = "hello"
let s = present!                            // "hello" (known non-nil at runtime)

let empty: String? = nil
let x = empty!                              // ❌ R007

Choose one of three: ?. chaining / ?? default / ! force unwrap.

Nil Coalescing ?? ​

swift
let opt: Int? = nil
let v = opt ?? 0                            // 0
let v2 = opt ?? (1 + 2)                    // 3 (the right side is an expression)

?? precedence: lower than comparison and logical; parentheses are recommended: let r = (a ?? 0) + 1.

if let / guard let ​

swift
func main() {
    let optional: Int? = 1
    // if let
    if let x = optional {
        print("got: \(x)")
    } else {
        print("nil")
    }

    // guard let (must exit early)
    guard let y = optional else {
        return
    }
    print(y)                                // Here y is not Optional
}

else must exit: if a guard let's else block does not return / throw / break / continue → compile error S020.

try ? ​

swift
func risky() throws -> String {
    return "ok"
}

func main() {
    let v = risky()?                        // String? (nil on failure)
    let v2 = try! risky()                   // String (panics on failure)
    print(v)
    print(v2)
}

Pattern Matching ​

swift
enum Result {
    case ok(Int)
    case err(String)
}

func main() {
    let result = Result.ok(1)
    switch (result) {
    case .ok(let v) where (v > 0) {
        print("ok: \(v)")
    }
    case .err(let e) {
        print("err: \(e)")
    }
    default { }
    }

    if case .err(let e) = result {
        print("err: \(e)")
    }
}

See Chapter 6, Control Flow and Chapter 9, Enumerations.

Identity === / !== ​

Reference- or type-sensitive equality subset:

swift
let a = "hi"
let b = "hi"
print(a === b)                              // false (different objects)
let c = a
print(a === c)                              // true (same reference)

Status: === MVP subset; commonly used for class / Object reference comparison.

Custom Equatable / Comparable ​

swift
@Equatable
struct Point {
    var x: Int
    var y: Int
}

struct Score: Comparable {
    var value: Int
    func compare(other: Score) -> Int {
        if (value < other.value) { return -1 }
        if (value > other.value) { return 1 }
        return 0
    }
}

@Equatable / @Hashable / @Codable macros: synthesize == / hash / encode / decode automatically (see Chapter 19, Macros).

Differences from Swift ​

SwiftSYX
Custom operatorsImplemented (infix / prefix / postfix)
Precedence / associativityImplemented (precedence 0–200)
Half-open ..< / closed ...Half-open Implemented; closed Partially implemented
Optional chaining ?.Implemented
Force unwrap !Implemented
Nil coalescing ??Implemented
===MVP subset
#availableNot implemented
Overflow behaviorAlways two's-complement wrapping (≠ Swift default trap; R011 panic not delivered; &+/&-/&* not implemented; unary -Int.min wraps, not trap GA)

Complete Example ​

text
// Custom operators + unicode √ — illustrative only (OUT this window)
infix operator |> { precedence: 50, associativity: left }
infix operator <^> { precedence: 60 }
prefix operator √
func main() {
    let r = 5 |> { $0 * 2 } |> { $0 + 1 }
    let side = √(16.0)
}

Diagnostics ​

CodeTriggerFix
S004Operand types mismatch on both sidesFix the types
S008Narrowing (e.g. Int64 → Int8)Check the range
S020guard let else does not exitAdd return / throw
R007! unwrapping nilUse ?. / ??

Next chapter → SIMD

See also → Language Reference: Expressions · Chapter 3, Basic Operators · Chapter 9, Enumerations

SYX · Apache-2.0