O'Reilly logo

Swift Quick Syntax Reference by Matthew Campbell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required