OneBite.Dev - Coding blog in a bite size

Convert Variable From String To Float In Swift

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

Swift is a robust and intuitive programming language created by Apple for iOS, Mac, Apple TV, and watchOS app development. It’s a modern language that provides safety, performance, and software design patterns that make your code clearer and easier to understand. In this article, we will learn how to convert a variable from string to float in Swift.

Code Snippet for Variable Conversion

Here is the Swift code snippet that you need to convert a variable from string to float:

let stringNumber = "3.14"
if let floatNumber = Float(stringNumber) {
  print(floatNumber)
} else {
  print("Invalid input")
}

Code Explanation for Variable Conversion

This code is simple and straightforward. Let us discuss it step by step.

  1. Firstly, we declare a string named stringNumber and assign a string literal containing a number to it. Note that this looks like a number but is in fact a string because of the quotation marks.

    let stringNumber = "3.14"
  2. Next, Swift’s Float( ) initializer is used to convert a string into a float. This creates a new Float instance representing the numeric value of the string if the string can be parsed as such. If the string can’t be parsed into a Float, it returns nil.

    if let floatNumber = Float(stringNumber) {
  3. When the conversion is successful, the floatNumber variable is displayed using the print( ) function.

    print(floatNumber)
  4. Otherwise, the block of code in the else statement will run, printing an error message “Invalid input”. This gives you some feedback that the string could not be converted to a Float.

    else {
     print("Invalid input")
    }

In conclusion, Swift provides a reliable way to convert a string to a float which can be useful in various programming situations where numeric manipulation is required. By checking whether the conversion results in an actual Float or nil, your code can handle both successful conversions and failures.

swift