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:
- 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.
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:
We can also ask swift to return the value in all UPPERCASE.
Swift can also help us convert Hexadecimal base 16/6 to an
Integer.