Workshop 15: Type Casting Functions

Type casting allows you to access a specific value as if it were of a different type. Type casting functions are available in Swift for type casting numbers and strings. In this workshop you learn how to use them. Casting a value using a Swift casting function create a new value that is a direct conversion of the original.

Before you begin, I assume you’ve done the following:


Number Casting Functions [number → number]

This section shows you how to use three functions for casting a number to another type of number.

Double(value) – This function casts the given value as a number (either integer or floating-point).

var grossPayDouble = Double(17) * 10.15
// Output

Float(value) – this function casts the given value as a number (either integer or double).

var grossPayFloat: Float = Float(17) * 10.15
// Output

Int(value) – This function casts the given value as a number (either double or floating-point).

var grossPayInt: Int = Int(17.55) * 10.15
// Output

String Casting Methods [string → number]

Swift provide several convenience methods for type casting a String literal, variable, or constant that have a number to a Float, a Double, or an Int type. This section shows you how to use five of them. All of the convenience methods below skip initial and trailing spaces and characters when they perform the type casting operation.

floatValue – This method typecast a String containing a number to a Float. Code below type cast a string literal, which contain a floating-point number to a Float.

var prodPrice: Float = ("3737.07").floatValue
// Output

doubleValue – This method type cast a String to a Double. Code below type cast a String literal which contain a Float to a Double.

var prodPrice = ("195.77").doubleValue
// Output

intValue – This method typecast a String to an Int. Code below type cast a String literal which contain a Float to an Int.

var aNumber = ("195.77").intValue
var result = aNumber * 4
// Output

On line 01 above, the string literal, which contain a floating-point value was type casted to an Int. If we didn’t do that, the compiler would have thrown an error shown below, when we try to use the aNumber variable in a multiplication calculation on line 02.

cannot invoke ‘*’ with an argument list of type ‘(@lvalue String, IntegerLiteralConvertible)’

boolValue – This method type cast a String to a Bool. Here is an example of how to use the boolValue method to type cast a string literal.

let theLightIsOn = ("Yes").boolValue
if theLightIsOn {
    println("Yes, the light IS on")
// Output
"Yes, the light IS on"

dataUSingEncoding() This method typecast a String to an NSData.

let sentence: NSString = "night watch man"
let data = sentence.dataUsingEncoding(NSUTF8StringEncoding)
// Output
"night watch man"