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:
Default value of 'boolean' and 'Boolean' in Java
Swift has a basic Boolean type, called Bool. Boolean values are referred to as logical, because they can only ever be true or false. Swift provides two Boolean constant values, true and false: The types of orangesAreOrange and turnipsAreDelicious have been inferred as Bool from the fact that they were initialized with Boolean literal values.
Use the Boolean Data Type (Visual Basic) to contain two-state values such as true/false, yes/no, or on/off. The default value of Boolean is False. Boolean values are not stored as numbers, and the stored values are not intended to be equivalent to numbers. You should never write code that relies on equivalent numeric values for True and False.
Swift provides its own versions of all fundamental C and Objective-C types, including Int for integers, Double and Float for floating-point values, Bool for Boolean values, and String for textual data. Swift also provides powerful versions of the three primary collection types, Array, Set, and Dictionary, as described in Collection Types.
Also, it does not depend on whether or not you calling another workflow or not. Even in the same workflow, if you don’t specify the boolean variable value and try to print it, it will come as false. Refer to this link for default values. Learn the default values of C# types such as bool, char, int, float, double and more.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With