Tuesday, 11 February 2025

Safe Type casting in Swift (Data Conversion)


When working with different types of Data in Swift, it's important to understand the best practices to convert data from one form to another. Let's take a look at this using below example: 

  1. Conversion between Int and String

When we type case an Int to a String using String(integer1), the new type is an optional type of string which can be little daunting to work with. Swift provides us with safe ways to convert Int to an String.

  • Using Optional Binding - This way, the print statement is only executed when string1 has a valid String value.
let int1 = 55
if let string1 = String(int1) {
   print(string1)  
}
  • Using nil coalescing - This method will assign a default value to the new variable when swift can not convert to a valid value:
let string2 = String(int1) ?? "N/A"

    2. Conversion between Int and Hexadecimal (Base 6 or Base 16)

let str3 = String(125, radix: 16) à This will return 7d

We can also ask swift to return the value in all UPPERCASE.

Str3 = String(125, radix: 16, uppercase: true) à This will return 7D

Swift can also help us convert Hexadecimal base 16/6 to an Integer.

let int2 = Int(“7D”, radix: 16)

No comments:

Post a Comment