5

Recently a co-worker has taken to checking boolean values in the following manner:

if boolVar.boolValue {
    ...
}

These variable are generally declared explicitly as boolean types either using:

var boolVar: Bool!

or

var boolVar = false

I am under the understanding that if a variable is declared as a boolean then it should be treated as such. Meaning it can only ever be true or false, so it should be treated as such and shouldn't need to dive in to the boolValue property which states it is exactly the same.

This is how Apple defines it:

extension Bool : BooleanType {
    /// Identical to `self`.
    public var boolValue: Bool { get }
    /// Construct an instance representing the same logical value as
    /// `value`.
    public init<T : BooleanType>(_ value: T)
}

It seems to me this is useful for creating your own types which conform to BooleanType. I also feel this .boolValue property may come in handy if unwrapping a boolean from a dictionary or a JSON response but it feels weird in this instance.

My question is, is there ever a case where we should be checking booleans in this manner?

  • 1
    All that, just for a boolean? – Robert Harvey Oct 25 '16 at 21:16
  • @RobertHarvey see that's my thing, booleans should just be true or false but thanks to Swift's ability to extend any type and certain co-workers obsession with minute details, this has become an issue. – Slayter Oct 26 '16 at 13:16
  • So what does the extension add that a simple bool variable doesn't provide? Does it provide a string representation of its value, i.e. "true" or "false"? Something else? – Robert Harvey Oct 26 '16 at 13:53
  • The extension listed above simply echos the value of the bool. For an actual bool variable I don't see what functionality it provides. But maybe for things extending BooleanType it may be useful? I don't know. But what he's doing is just weird to me. – Slayter Oct 26 '16 at 14:03
  • 1
    BooleanType was a protocol to describe types which can be used in control statements like if. It has been removed in Swift 3. – Martin R Jan 4 '17 at 11:03
1

Never, for several reasons:

  1. BooleanType was removed in Swift 3.
  2. The implementation of .boolValue for Bool just returns self. Why stop at just one .boolValue? Why not boolVar.boolValue.boolValue.boolValue.boolValue.boolValue.boolValue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.