OneBite.Dev - Coding blog in a bite size

Convert Variable From Int To Float In Swift

Code snippet for how to Convert Variable From Int To Float In Swift with sample and detail explanation

Converting variables from one datatype to another is a common task in programming. In this article, we will specifically see how to change a variable from an integer to a float in Swift programming language.

Code snippet: Convert Variable From Int To Float In Swift

To start with, here is a simple code snippet in Swift to convert a variable from integer to float.

var numberInt: Int = 10
var numberFloat: Float

numberFloat = Float(numberInt)

With this code, we are converting an integer into a float successfully. The integer number 10 is reassigned to a float variable numberFloat.

Code Explanation: Convert Variable From Int To Float In Swift

Swift is strictly a type-safe language. Meaning, you cannot mix different types of variables arbitrarily because each type has a specific storage size and underlying representation. However, Swift allows us to convert one type of variable to another using a method known as Type Casting.

In the above code snippet, we first initialize an integer variable numberInt with an integer value of 10.

var numberInt: Int = 10

Then, we declare a float variable numberFloat without assigning any initial value.

var numberFloat: Float

Next, we use Swift’s built-in Type Casting feature to convert the integer numberInt into a float, and then assign this new float value to the numberFloat variable.

numberFloat = Float(numberInt)

This simple line of code makes Swift convert the value stored in numberInt into a Float type and assigns this new floating point value to numberFloat. The key here is the use of Float() type casting function which facilitates this conversion.

And that’s how you convert one variable from an integer to a float in Swift. But remember, being a strict type-safe language, Swift will not automatically convert types for you. Thus, you need to explicitly convert variables from one type to another when needed.

swift