Type Casting and Type Checking

Discover how Swift data types may be related to each other while exploring the concepts of type casting and type identification.

Type casting

When writing Swift code, situations will occur where the compiler is unable to identify the specific type of a value. This is often the case when a value of ambiguous or unexpected type is returned from a method or function call. In this situation, it may be necessary to let the compiler know the type of value that your code is expecting or requires using the as keyword (a concept referred to as type casting).

The following code, for example, lets the compiler know that the value returned from a method named object(forKey:) needs to be treated as a String type:

let myValue = record.object(forKey: "comment") as! String

Upcasting

In fact, there are two types of casting which are referred to as upcasting and downcasting. Upcasting occurs when an object of a particular class is cast to one of its superclasses. Upcasting is performed using the as keyword and is also referred to as guaranteed conversion since the compiler can tell from the code that the cast will be successful.

When using Swift to develop apps for iOS, for example, you may find yourself working with a set of classes from the UIKit framework used to design user interface layouts. For example, the UIButton class is used to display a button control on the screen and is a subclass of the UIControl class (which is within itself a subclass of UIView) as shown in the fragment of the UIKit class hierarchy shown below:

Get hands-on with 1200+ tech skills courses.