Swift: Structure Methods

Methods of Structure in Swift:

We can provide our structs with custom methods that instances can call in addition to the init() method. These instance methods of structure in Swift are created similarly to regular functions, but within the structure’s scope:

struct Car {
  var name : String; 
  var speed : Int ;
 
  init (name : String, speed : Int) {
    self.name = name ;
    self.speed = speed ;
  }

  // We've added a start() method:
  func start() {
    print("Car's start!") ;
  }
};

We added a method start() using the func keyword in the previous example; it has no parameters and returns nothing. The method syntax is similar to that of a function, with the exception that a method is specific to the structure’s instances.

Now we can make a Car object with the .start() method:

var racingCar = Car(name : "BMW i8", speed : 340) ;
racingCar.start() ; // Prints: Car's start!

We can call the method using dot syntax and a pair of parentheses after the method name after we’ve defined our instance, racingCar.

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: