Downcasting in Swift 1.2 with the as! Operator

Introduction

Apple continues to improve Swift in its quest to create a modern, powerful and safe programming language for its family of devices powered by iOS and OS X. Swift 1.2, currently in beta, brings a handful of new language features, one of which is the as! operator for failable casts.

Type Casting

Downcasting is part of the more general topic of Type Casting. Type casting allows us (1) to check the type of an instance of a class or (2) to treat the instance as a superclass or subclass of that class — within its own class hierarchy. I won’t define type casting in terms of the so-called fundamental types since Swift provides its own versions of all fundamental C and Objective-C types in the form of classes.

In Swift, type casting is implemented with the is and as operators, the former allowing us to check type and the latter allowing us to cast a value to a different type.

Checking Type with is

To illustrate is, let’s define some classes that represent a rudimentary file system. We’ll define a base File type that can represent any file within our file system.

Swift

And two derived file types to represent a text file and an image.

Now to populate an array of some text and image files.

If we were to iterate through the files array, we’d need to do so using the base class since we don’t know what type of file we’ll be looking at in each iteration until we do some is probing.

In the above code snippet, we accessed the name property of each file. However, we weren’t able to access any of the properties specific to text files or images because our variable file is of type File and the File class doesn’t know anything about its subclasses. We can, however, cast file downwards into our class hierarchy in order to access properties and functions specific to the subclasses. As of Swift 1.2, there are now three flavours of as:

Upcasting with the as Operator

Guaranteed Conversion

When a conversion can be guaranteed to succeed and therefore not be the cause of an app crash, the conversion can be represented by as. This must be determinable at compile time by the Swift compiler. An example of a guaranteed conversion is upcasting. An Image object can be casted to a File type, guaranteed, because an Image is a File (though a File is not necessarily an Image).

Downcasting with the as? Operator

Optional Conversion

If you’re not sure if your conversion will succeed, you’ll need to use as?. As with other optional operators, as? always returns an optional value. If the conversion fails, the value will be nil.

Downcasting with the as! Operator

Forced Conversion

Prior to Swift 1.2, as was also used for forced conversion. Swift 1.2 now represents forced conversions with as! to make it clear that the conversion may fail if you attempt to downcast to a type that doesn’t actually represent the value’s type. For example, if you have a variable of type File that represents an Image and you attempt to downcast it to a TextFile, the conversion will fail. If you attempted to downcast it with as!, a runtime error would be triggered.

It’s worth noting that you should always try to avoid using as!. Apple removed forced conversion with as and created as! specifically for this so that it stands out as a warning that the conversion will emit a runtime error, i.e. crash, if the forced conversion fails. Having said this, the Swift-er way to write the above would be with optional downcasting.

Conclusion

Swift 1.2 goes that extra step again towards avoiding runtime errors by distinguishing between guaranteed and forced type casting. When we downcast, Swift isn’t able to determine at compile time if the conversion will succeed and we therefore turn to optional and forced conversions. Optional conversions are safer to use and should be used when possible. Forced conversions are now marked with a ! and are meant to help you spot potentially dangerous code more easily.

Ryan started programming at an early age of 10 and quickly chose to focus on C-based languages throughout his software development career and on iOS app development starting with the iPhone SDK released in 2008. He now specializes in iOS app development with C, C++, Objective-C and Swift as well as React and React Native app development. When he is not programming, he's usually honing his skills in human-based languages, including Spanish, French and Mandarin Chinese. Born in Trinidad, W.I., his travels have taken him all over North America, Europe and Asia. He still has his eyes set on South America.

0 Comments

Leave a reply