Swift: New Type

New Type in Swift:

We’ve done a lot with structures in the previous exercises: we’ve created a structure, created instances, added properties and methods, and so on. So take a moment to think about what we’ve accomplished: we’ve created a code model of a real-world object! We also created a new data type in our program in Swift as a result of this!

Let’s go over our previous example again:

struct Car {
  var name = ""; 
  var speed = 0 ;

var racingCar = Car() ;

We can use Swift’s built-in type(of:) function to determine the type of racingCar:

type(of: racingCar) ; // Car

RacingCar is, in fact, a Car type. Remember that we can also give our variables an explicit type. Let’s pretend we have a second car called hatchbackCar:

var hatchbackCar = Car() ;

It’s important to note that the type of hatchbackCar can be specified as Car. This means that we can use structures within structures as property values as well:

struct Vehicle {
  var newCar: Car ;
  var newBus: Bus ;

Another structure, Vehicle, was created above to assist us in keeping track of our new vehicles. We typed Car for the newCar property. We also added the newBus property for when we create a Bus structure. With the ability to create new types, we can model more complex real-world objects!

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: