Book Image

Application Development with Swift

By : Hossam Ghareeb
Book Image

Application Development with Swift

By: Hossam Ghareeb

Overview of this book

Table of Contents (14 chapters)

Type casting and type checking

Type casting and checking are ways used in Swift to check the type of instances and cast them to any different type. In Swift, we use as and is to perform type casting and type checking. Before going deep into how to use these operators, let's build an array that we will use in next examples:

var subViews = [UILabel(), UIButton(), UILabel(), UITextField(), UITextView()]

We created an array of UI controls, but you might question, "how did you create array of objects of different types in Swift when you told us that Swift array is typed?" My answer is yes, you are right, but the Swift compiler is smart enough to check the items of the array; if they are different in type, it will search for the common superclass for them, which is UIView. So, this array is of type UIView.

Now, let's see how to check the type of items of this array. We will use the is operator followed by class name. Check the following code:

var labelsCount = 0
for view in subViews
    if view...