What is the default value of a basic Boolean in Swift?

Bool, Bool! and Bool? all are different in Swift.

1. Bool is a non-optional data type that can have values - true/false. You need to initialize it in the initializer or while declaring it before using it.

var x : Bool = false

var x: Bool
init()
{
   x = false
}

2. Bool? is an optional data type that can have values - nil/true/false. In order to use this type, you need to unwrap it using if let or force unwrapping.

var x: Bool?

if let value = x
{
   //TODO: use value instead of x
}

3. Bool! is an implicitly unwrapped optional data type that can have values - nil/true/false. The difference here is it must contain a value before using it else it will result in runtime exception. Since it is implicitly unwrapped, no need to unwrap it using if let or force unwrapping.

var x: Bool! //Must contain value before using

Strictly spoken there is no default value in Swift.

  • Either the Bool is non-optional then you have to assign a (default) value
  • or if the Bool is an optional, then it is nil – which is no value in terms of Swift.

Tags:

Boolean

Swift