Search⌘ K

Type Casting and Type Checking

Explore type casting and type checking in Swift to understand how to handle ambiguous data types. Learn the differences between upcasting and downcasting, how to safely cast types using conditional downcasting, and how to verify object types with type checking. Gain foundational skills to manage types effectively in your Swift code.

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 ...