Why does Swift reject `if count { … }` for an Int and `1 < x < 10`, and how do `&&` and `?:` evaluate?
answer
- no truthiness in conditions
- comparison group has no associativity
- right operand is an autoclosure
- one branch, one common type
basics
~20 sA Swift boolean condition must be a Bool, and comparison operators are non-associative, so if count and 1 < x < 10 are rejected. && and || skip the right operand once the left decides; ?: evaluates one branch, and both branches share a type.
solid answer
~50 sSwift has no truthiness: a boolean condition in an `if`, `while` or `guard` must be a `Bool` expression, so `if count` fails with "type 'Int' cannot be used as a boolean; test for '!= 0' instead", and `if x = 5` is caught as "use of '=' in a boolean context, did you mean '=='?". The comparison operators share `ComparisonPrecedence`, which declares no associativity, so `1 < x < 10` is rejected; write `x > 1 && x < 10`. `&&` and `||` take their right operand as an `@autoclosure`, so it runs only when the left side has not already decided the result, and `&&` binds tighter than `||`. The ternary `c ? a : b` evaluates only one branch, and both branches must have a common type, or the compiler reports mismatching types.
code
swift · 19 lineslet items = [4, 0, 7]
let index = 5
func isFeatured(_ value: Int) -> Bool {
print("checked \(value)")
return value > 5
}
// The right operand runs only when the left one is true,
// so the out-of-range subscript is never evaluated.
if index < items.count && isFeatured(items[index]) {
print("featured")
}
let x = 4
let inRange = x > 1 && x < 10 // not 1 < x < 10
let label = items.isEmpty ? "none" : "\(items.count) items"
print(inRange, label) // true 3 items
print((1, "zebra") < (2, "apple")) // true: the first elements decidego deeper
Recall that boolean conditions must be Bool values, that comparisons do not chain, and that && stops at the first false while || stops at the first true.
Explain short-circuiting through the autoclosure right operand, the order of the comparison, && and || precedence groups, and the common-type rule for ternary branches.
Use evaluation order deliberately: put a bounds check or cheap test first so a trapping or costly right operand never runs, and keep side effects out of it.
Set a readable house style for conditions: parentheses whenever && and || mix, no nested ternaries, and if or switch expressions for anything beyond two outcomes.
## Conditions must be Bool Swift has **no truthiness**. A boolean condition in an `if`, `while`, `guard` or ternary must be an expression of type `Bool`; an `Int`, an `Optional` or a collection is never silently treated as true or false. (Optional binding with `if let` and pattern conditions with `if case` are separate condition forms, not values converted to `Bool`.) The compiler names the fix: - `if count { … }` with an `Int` fails with `type 'Int' cannot be used as a boolean; test for '!= 0' instead`. - `if x = 5 { … }` fails with `use of '=' in a boolean context, did you mean '=='?`. Assignment in Swift returns no value, so the classic typo cannot slip through. Write the comparison you mean: `count != 0`, `!items.isEmpty`, `name != nil`. ## Comparison operators do not chain Every infix operator belongs to a **precedence group** that fixes how tightly it binds and how a run of same-group operators groups. The standard library declares these groups for the operators in this question: | Group | Operators | Associativity | Effect | |---|---|---|---| | `ComparisonPrecedence` | `==` `!=` `<` `<=` `>` `>=` | none | `1 < x < 10` is rejected | | `LogicalConjunctionPrecedence` | `&&` | left | binds tighter than `\|\|` | | `LogicalDisjunctionPrecedence` | `\|\|` | left | binds looser than `&&` | | `TernaryPrecedence` | `?:` | right | nested ternaries group to the right | Because `ComparisonPrecedence` declares no associativity, `1 < x < 10` fails with `adjacent operators are in non-associative precedence group 'ComparisonPrecedence'`. Write `x > 1 && x < 10`, or `(2..<10).contains(x)` for integers. Tuples compare too: two tuples of the same type with fewer than seven elements, whose elements all support the operator, compare left to right, and the first unequal pair decides. `(1, "zebra") < (2, "apple")` is `true` without ever comparing the strings. ## Short-circuit evaluation `&&` and `||` are ordinary functions in the standard library, but their right parameter is an `@autoclosure () throws -> Bool`. The expression you write on the right is wrapped in a closure that the operator calls only when it still matters: - `a && b` evaluates `b` only when `a` is `true`. - `a || b` evaluates `b` only when `a` is `false`. - Because the closure may throw, both operators are `rethrows`, so `try` works on the right side. That order is a tool: 1. Put the guard first: `index < items.count && items[index] > 0` never runs the subscript when it would trap. 2. Put the cheap test before the expensive one: `cache.isEmpty || expensiveCheck()`. 3. Keep side effects out of the right operand, because whether they happen depends on the left one. `!` is the prefix logical NOT; `!isReady && hasData` applies `!` first, since prefix operators bind tighter than any infix operator. ## The ternary conditional `condition ? a : b` is an expression that evaluates **only the chosen branch**. Two rules catch people: - Both branches must produce one common type. `flag ? "a" : 1` fails with `result values in '? :' expression have mismatching types 'String' and 'Int'`. - The ternary is right-associative, so `a ? b : c ? d : e` reads as `a ? b : (c ? d : e)`. It works, but a nested chain is hard to review; for more than two outcomes an `if` or `switch` expression, covered with control flow, reads better. ## What to remember - Boolean conditions are `Bool`, always; nothing converts implicitly. - Comparisons do not chain. - `&&` binds tighter than `||`, and both stop as soon as the result is known. - A ternary picks one branch, and both branches share one type.
- How can `&&` short-circuit if it is an ordinary standard-library function?Its right parameter is declared `@autoclosure () throws -> Bool`. The caller's right-hand expression is wrapped in a closure, and `&&` calls that closure only when the left side is `true` (`||` only when it is `false`). Because the closure may throw, the operators are `rethrows`, so `try` is allowed on the right side.
- How does `a || b && c` group in Swift?`&&` lives in `LogicalConjunctionPrecedence`, declared higher than `LogicalDisjunctionPrecedence` where `||` lives, so it groups as `a || (b && c)`. Both groups are left-associative, so `a && b && c` is `(a && b) && c`. Parentheses are still worth adding when mixing them, so readers need not recall the table.
- A non-zero Int counts as true in an if condition
- 1 < x < 10 checks that x lies between 1 and 10
- Both operands of && are evaluated before the result is known
- A ternary's branches may return different types, such as String and Int
- && and || share one precedence level and group strictly left to right