Swift - Data Type Type Conversion

Introduction

In Swift, there is no implicit conversion.

You need to perform explicit conversion whenever you want to convert a variable from one type to another type.

Consider the following statement:

var s1 = "400"

By type inheritance, s1 is String.

To convert it into an Int type, you need to use the toInt() method to explicitly convert it:

var amount1:Int? = s1.toInt ()

You must specify the ? character to indicate that this is an optional type; otherwise, the type conversion will fail.

You can rewrite the preceding example to use type inference:

var amount1 = s1.toInt ()

Consider another example:

var s2 = "1.25"

If you call the toInt() method to explicitly convert it to the Int type, you will get a nil :

var amount2 = s2.toInt()   //nil as string cannot be converted to Int

If you call the toDouble() method to explicitly convert it to the Double type, you will get an error:

var amount2:Double = s2.toDouble()  //error

To fix this, you can cast it to NSString and use the doubleValue property:

var amount2: Double = (s2 as NSString).doubleValue  //1.25

Convert from numeric values to String types

To convert from numeric values to String types:

var num1 = 200     //num1 is Int
var num2 = 1.25    //num2 is Double

To convert the num1 of type Int, you can use the String initializer:

var s3 = String(num1)

Alternatively, you can use the string interpolation method:

var s3 = "\(num1)"

To convert the num2 of type Double, you cannot use the String initializer, as it does not accept an argument of type Double:

var s4 = String(num2) //error

Instead, you have to use the string interpolation method:

var s4 = "\(num2)"

Related Topic