Swift Float

In this tutorial, we will learn more about Swift float datatype like initialization, manipulation, printing etc.

Swift Float is used to store single-precision, floating-point value type.

Float Declaration

To declare a variable to store float datatype, use the following syntax.

</>
Copy
  var variableName :Float

Float Initialization

To initialize the variable, you can provide the value while declaring the variable.

</>
Copy
  var pi :Float = 3.14159

Print Float to Console

To print the float variable to console, use print() method.

main.swift

</>
Copy
var pi :Float = 3.14159 
print(pi)

Output

3.14159

Float Initialization using Float.init()

Swift 4 uses type inference. What does that mean? It means that if you initialize a variable with float value during declaration, you can skip telling the compiler that the variable is of Float type. Based on the value you assign to the variable, compiler deduces the datatype.

main.swift

var pi = Float(3.14159)
print(pi)
print(type(of:pi))

Output

3.14159
Float

Conclusion

In this Swift Tutorial, we have learned about Float datatype and how to use it Swift programming.