I want to know about Bool
in Swift.
If Bool is a basic primitive datatype, why is a Boolean's default value nil
?
var test: Bool!
print(test) // nil
In Java the Boolean default value is false:
I want to know about Bool
in Swift.
If Bool is a basic primitive datatype, why is a Boolean's default value nil
?
var test: Bool!
print(test) // nil
In Java the Boolean default value is false:
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.
Bool
is non-optional then you have to assign a (default) valueBool
is an optional, then it is nil
– which is no value in terms of Swift.Bool
in Swift is not a primitive. Everything in Swift are objects. Your variable test
is a Bool!
, which is an implicitly unwrapped optional and the default value is nil
.
If you use this code (not an optional),
var test: Bool
print(test)
You will get an error:
variable 'test' used before being initialized
So in Swift you have to initialize stuff before you use it, for example:
var test: Bool = false