Created by Apple in 2014, Swift is a popular open source language for building iOS apps that has gained a strong developer community and a wealth of third-party content.

Like almost all other programming languages, Swift has its own rules and syntax. In this guide, we’ll look at type conversions in Swift, a popular concept in modern object-oriented programming languages.

What is a type in Swift?

Essentially, a type is a primitive equivalent of a class that represents the kind of data stored in a variable. Because each class is different from the others, the data type is also different, allowing developers to distinguish variables based on the data type they hold. Classifying data types prevents type mismatches, a common compile-time error.

To the compiler, types are irrelevant. If the data stored in a variable matches an action later in the process, the process runs accordingly.

However, if the type mismatch causes the process to break, you will see a compilation error. Even if a type mismatch does not explicitly break the process, it may go unnoticed during compilation, leading to unexpected results when the program runs.

Swift is a strongly typed programming language. Each variable in Swift has a type associated with it, and once a type is assigned to a variable, it cannot store any other type of data.

Weakly typed languages are less strict in this respect. For example, in languages like PHP and C, you can change data types to some extent to gain more flexibility in your code.

What is a cast?

The limitation of usage types forces a language to lose much of its flexibility. Conversions provide a way to gain some flexibility.

Not all class variables hold raw data like integers and strings. Much of the logic of modern applications relies on custom objects, which are implemented through classes. From now on, we will refer to primitive data types and classes as types.

Conversion is a programming paradigm used in most object-oriented languages that allows developers to treat objects of one type as objects of another type. While type conversions may not make sense at first, they help simplify many programs in modern applications.

Type conversions do not change the associated objects. Instead, it changes the type used to describe the object. For example, you obviously can’t change the type of an object that holds a string from String to INTEGER, because in real life it doesn’t make sense to think of a sentence as a number.

In order for type conversions to occur, the original and new types of related objects must be subclasses or superclasses of each other. Suppose a class called Vehicle has two subclasses, Car and Truck. You can assign an object of type Car to Vehicle and vice versa; Or Truck to Vehicle and vice versa.

Now, suppose we have another class called Ship that has nothing to do with Truck, Car, or Vehicle. You will not be able to cast its objects into any of the types given above.

On the pitch

The upcast is used to generalize a series of subclasses of a class by using its own variables. Let’s consider the Car,Truck, and Vehicle examples.

As we mentioned earlier, Car or Truck can be type-converted to Vehicle. Objects of a subclass are typed to objects of their superclass. Think of it as moving up the hierarchy of classes.

Upvotes allow you to store any type of Vehicle in a Vehicle reference: Car,Truck, etc. We already know that these are all descendants of the same class, Vehicle, and they must have some similarities. Uploading their objects to the Vehicle class, using this generalization, lets run operations using loops and other normal paradigms.

Here is an example of an upload method.

let truck:Truck = Vehicle(wheels:8)
Copy the code

In the code block above, you declare a reference named truck, which is of type truck. Next, you initialize it with an instance of Vehicle that has eight wheels. You can see that the type annotation of a reference variable is completely different from the object assigned to it.

As mentioned earlier, we can do this because Truck and Vehicle belong to the same class hierarchy. This is exactly as logically correct as saying that a truck is a vehicle.

In the example above, the playback is implied. However, you can make it visible by running the following code.

let truck:Truck = Vehicle(wheels:8) as Truck
Copy the code

We’ll cover implicit podcasting in more detail later.

Under the

A drop is the opposite of a drop and refers to the casting of an object of a parent type to an object of its subclass. A drop is used to recast a previously upcast subclass object for generalization.

Let’s say you own two cars and three trucks. If you store them in a shared array, type reasoning will determine that the array is of type Vehicle, which is the common parent of both types.

If you try to get an item from an array, you get an object of type Vehicle. To change it back to its original type, you need to move it down to a Truck or Vehicle.

It is important to understand that not all vehicles in the list are cars, which may cause the downconversion to fail in some cases. To solve this problem, we will use two types of underscore operators, which we will describe later.

Horizontal type conversion

Note that Car and Truck have a common superclass, but you cannot throw an object of type Car into Truck or vice versa. They are neither subclasses nor superclasses of each other. Therefore, horizontal casting is ineffective, and if you try to cast a Car into a Truck, you will get an error.

Type conversion operations in Swift

To perform the above operations, you will use the following operators.

as

The AS operator is used to throw objects. However, in most cases, the drop is done implicitly, so you won’t use as very often.

Again, here’s an example of uploading Chair to Furniture.

let furniture:Furniture = Chair(legs: 4) as Furniture
Copy the code

as?

as? The operator is used for optional drop down and is one of the two drop down operators available in Swift. When you are not sure whether an object can be successfully uploaded, use as? .

If you try to move an object down from a different class hierarchy, your program will return nil if it encounters an error. To verify that the down conversion is successful, you can put a simple check for nil.

You can use as? In our Vehicle example. Operators.

let truckObject = vehiclesArray[0] as? Truck
Copy the code

You instruct the control to access the first object in the array, pass it down to a Truck, and store the result in the truckObject variable.

If the drop succeeds, you will find a Truck instance in the truckObject. If it fails, truckObject will point to nil. And then you can check for nil by running it.

if truckObject ! = nil { print("The reference points to some value!" ) } else { print("The reference points to nil, and so the downcast was unsuccessful") }Copy the code

as!

as! The operator is used to force down conversions and returns an object only when a type conversion operation is possible. If you try to move an object down from a different class hierarchy, your program will encounter a fatal error.

Here’s how you can use AS! Operator with our Vehicle example.

let carObject = vehiclesArray[1] as! Car
Copy the code

The above line instructs the control to access the second object from the array, move it down to a Truck, and store the result in the truckObject variable. If the downconversion fails, the program crashes.

With these points in mind, you should only use as! If you are sure that the object you are passing down belongs to a hierarchy of classes. Operator, and the operation completes successfully.

You can also use as! Operator: If the types do not match, the flow of the code needs to be interrupted, indicating that there may be unexpected results in the intermediate calculation.

is

The IS operator is used to check the type of an instance. The result of type checking using the IS operator is Bool, which indicates whether the types match, as shown in the following code block.

let car: Car = Car(wheels: 4)

if car is Car {
print("It is a Car.")
} else if car is Truck {
print("It is a Truck.")
}
Copy the code

The output is zero.

It is a Car.
Copy the code

You can also use the IS operator to check for any implicit upcasts. Let’s consider an example.

let car: Car = Vehicle(wheels: 4)

print(car is Car)
print(car is Truck)
print(car is Vehicle)
Copy the code

The output of the above code is:.

true
false
true
Copy the code

The output shows that the type of the Car reference is Car and the type of the implicit playback is Vehicle. Since horizontal projection is impossible, Car cannot belong to Truck.

Try it out for yourself

In this article, you learned about types and type casting in Swift, and covered the various operators used for type casting objects.

Type conversions are a concept that makes object-oriented programming very powerful and flexible. With the ability to move up and down the hierarchy of classes by casting up and down, you can leverage generalization as needed.

The key to retaining all information is practice. I hope you enjoy this article. Happy coding

The postType casting in Swift appeared first onLogRocket Blog.