← Back to archive

Development · Swift

Comparison, logical, and bitwise operators in Swift

Build Boolean conditions, combine them with logical operators, and use OptionSet for meaningful bit flags.

Read the Korean original on Velog ↗English translation

Development archive cover

Operators compare values and combine conditions to guide a program's decisions. Comparison and logical operations produce Boolean results used by branches and loops.

Comparison and logical operations

let first = 1
let second = 2

first == 1       // true
first != second  // true
first < second   // true

let isSignedIn = true
let hasPermission = false
isSignedIn && hasPermission // false
isSignedIn || hasPermission // true
!isSignedIn                 // false

&& is true only when both operands are true; || is true when at least one is true. Both short-circuit: once the result is known, the remaining expression is not evaluated.

Bitwise operations and OptionSet

Bitwise & and | operate on individual bits in integer values. When several options need to fit into one value, OptionSet gives those bits meaning more clearly than a raw integer.

struct Genres: OptionSet {
    let rawValue: Int
    static let pop = Genres(rawValue: 1 << 0)
    static let hiphop = Genres(rawValue: 1 << 1)
}

let favorites: Genres = [.pop, .hiphop]
favorites.contains(.pop) // true

Use comparison and logical operators for ordinary decisions. Choose bitwise operations when the problem actually requires combining or inspecting bits.

← Back to archive