Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

boolean

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

like image 513
Gaurav Saini Avatar asked Sep 11 '17 11:09

Gaurav Saini


People also ask

What is the Boolean type in Swift?

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.

What is the default value of a Boolean?

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.

What are the different types of data in Swift?

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.

Why can’t I print a Boolean variable in a workflow?

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.


1 Answers

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
like image 109
PGDev Avatar answered Oct 12 '22 12:10

PGDev