In many programming languages—C, C++, Ruby, JavaScript—you’ll find the idea of “true-ish” values. These aren’t exactly Boolean values, but can act like them in some cases.
It’s not always consistent, of course. If you have an int
in C, a zero value acts like Boolean false
and a non-zero value acts like true
. In Ruby, on the other hand, the existence of any non-nil value—including zero—is true-ish.
Type Specificity
Swift takes the approach where only Booleans are Booleans. This is valid C:
if (42) {
// this will print!
printf("42 is the truth!");
}
But this code generates a compile error in Swift:
// Error: type 'Int' does not conform to protocol 'BooleanType'
if 42 {
print("42 is the truth!")
}
Hmmm, BooleanType
you say?
BooleanType the Protocol
Turns out that what makes Bool
a Bool
is that it conforms to BooleanType
:
public protocol BooleanType {
public var boolValue: Bool { get }
}
That means you can make any type act in a Boolean-like manner. Your bare integers can be in conditions as in C, or you can recreate the Swift 1.0 beta behavior of optionals, where nil
was false
-ish.
Just keep the following comment from the headers in mind:
Only three types provided by Swift,
Bool
,DarwinBoolean
, andObjCBool
, conform toBooleanType
. Expanding this set to include types that represent more than simple boolean values is discouraged.
Who listens to docblock comments though, amirite? ;)
// I declare non-empty arrays to be `true`.
extension Array: BooleanType {
public var boolValue: Bool {
return self.count > 0
}
}
Check out the “Boolean All The Things” playground I’ve created for some code examples. What do you think? Would you rate it a true
or false
?