How to declare a float variable in Swift

In this tutorial, we will be learning how to declare a float variable in Swift with some simple examples.

You can also run the codes in Xcode that is built for Swift programming, more specifically to develop iOS and macOS applications.

To make it easier to understand. We will do the following things:

  • We will declare a Float variable
  • We will print the float variable value
  • Then we will also check the data type of that variable.
var myNumber:Float = 18.789

By using the above piece of code we have declared a Float variable.

The variable name is myNumber and the data type is float. The value of that float variable is 18.789

The syntax to declare a float variable in Swift

var variableName: Datatype = float_value

The data type will be float in this case.

How to print a float value in Swift

var myNumber:Float = 18.789
print(myNumber)

Output:

18.789

You can also read: Create a playground in Xcode 13 and newer versions

Can we assign an integer value to a float variable in Swift:

Yes we can, just check the below code and output

var myNumber:Float = 18
print(myNumber)

Output:

18.0

As we can see it automatically places .0 after our value.

Check if a variable is Float or not in Swift

var myNumber:Float = 18.789
print(myNumber)
print(type(of: myNumber))

Output:

18.789
Float

Another method to initialize a float variable

var myNumber = Float(18.78)
print(myNumber)
print(type(of: myNumber))

Output:

18.78
Float

We can also initialize in this way.

Some of you might think that what will happen if you don’t declare any data type?

Have a look at this too.

var myNumber = 18.78
print(myNumber)
print(type(of: myNumber))

Output:

18.78
Double

Leave a Reply

Your email address will not be published. Required fields are marked *