OneBite.Dev - Coding blog in a bite size

Convert Variable From String To Boolean In Swift

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

In the world of programming, converting data types is a common task, and it becomes particularly crucial when dealing with user inputs or data fetched from an API. This article will guide you through converting a variable from a string to a boolean in the Swift programming language.

Code snippet for Conversion of Variable From String to Boolean in Swift

Swift includes several built-in methods for converting variables to different data types, although there is no direct method for converting a string to a boolean. Below is a simple workaround to achieve this.

let stringVar = "true"
let boolVar = (stringVar as NSString).boolValue
print(boolVar) 

Code Explanation for Conversion of Variable From String to Boolean in Swift

The conversion process is fairly straightforward. The following are the detailed steps:

  1. Create your string variable - In the first line, we declare a variable stringVar of type string and assign it a boolean value in string format. Note that boolean values can be either “true” or “false”.

  2. Convert the string to a boolean - The second line of the code snippet is where the conversion happens. Swift’s NSString class enables us to convert a string variable to a boolean. The as keyword is used to cast stringVar to NSString. Then, we use boolValue, a property of NSString that returns a Boolean representation of the string.

    So (stringVar as NSString).boolValue is converting the string “true” to its actual boolean representation i.e true.

  3. Print the result - The third line of the snippet simply prints the boolean value. If stringVar was “true”, boolVar is printed as true. If stringVar was “false”, boolVar would be printed as false. If stringVar was not a valid format of a boolean (i.e. other than “true” or “false”), boolVar would be false.

Remember, Swift is case-sensitive. Therefore, “True” or “TRUE” would not convert to true. They would convert to false, which may be unintuitive, so be careful with the case when dealing with string input that needs to be converted to a boolean value.

In conclusion, converting a string variable to a boolean value in Swift, while not having a direct method, can be achieved using type casting and the boolValue property with relative ease.

swift