Swift Methods (Instance, Type) Example

1. Introduction

In Swift, methods are functions associated with a particular type. Swift provides two types of methods: instance methods and type methods. Instance methods are called on an instance of a type, while type methods are called on the type itself.

2. Source Code Example

// Define a structure for a counter struct Counter { // Instance property to store count var count = 0 // Instance method to increase the count func increment() -> Int { return count + 1 } // Instance method with parameter to increase the count by a specific value func increment(by amount: Int) -> Int { return count + amount } // Type method to give general information static func generalInfo() -> String { return "This is a simple counter." } } // Create an instance of the Counter structure var myCounter = Counter() // Call the instance methods print("Incremented count: \(myCounter.increment())") // Using the instance method 'increment' print("Incremented count by 5: \(myCounter.increment(by: 5))") // Using the instance method 'increment' with a parameter // Calling the type method print(Counter.generalInfo()) 

Output:

Incremented count: 1 Incremented count by 5: 5 This is a simple counter. 

3. Step By Step Explanation

1. We start by defining a Counter struct with an instance property count.

2. Next, two instance methods are defined:

a. increment() - which increments the count by 1.b. increment(by:) - which increments the count by a given amount.

3. A type method generalInfo is also defined, which provides some general information about the structure. Note that this method is marked with the keyword static, denoting it's a type method.

4. We then initialize an instance of the Counter struct named myCounter.

5. The instance methods are called on the myCounter instance and the results are printed.

6. Lastly, the type method generalInfo is called on the Counter type itself, not on an instance, and its result is printed.


Comments