Chapter    43

Type Casting

You can convert value types such as floating-point and integer numbers to other types in Swift. This is called type casting. Obviously, if you convert a Double type to a Float or Int type, you will lose some precision in your numbers. Listing 43-1 shows some examples of how you might convert a floating-point number to other value types.

Listing 43-1. Type Casting Value Types

let f1 = 9.99let i1 = Int(f1)let d1 = Double(f1)let b1 = Bool(f1)let s1 = toString(f1)

In Listing 43-1, you type cast f1 to an integer, double, and boolean. In the last line, you converted f1 to a String type.

Type Casting Instances

You can type cast instances using the as keyword. Let’s say you are using the Person and Employee classes from

Get Swift Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.