Javatpoint Logo
Javatpoint Logo

Swift4 Methods

In Swift4, methods are the functions which are associated with a particular type. In Objective-C, classes are used to define methods whereas in Swift4, we have methods for Classes, Structures and Enumerations.

Instance Methods

Instance methods are the methods which are associated with instances of class, structure or enum. Instance methods are written inside the body of that type.

Instance methods provide functionalities related to instance's need and also to access and modify instance properties. Instance methods are written inside the curly barces {}. It has implicit access to methods and properties of the type instance. When a specific instance of the type is called, it will get access to that particular instance.




Result is: 480
Result is: 450

In the above example, class calculate defines two instance methods:

  • init() is defined to add two numbers a and b and store it in result 'res'.
  • tot() is used to subtract the 'res' from passing 'c' value.

Local and External Parameter Names

In Swift4, function can describe both local and global declarations for their variables. The characteristics of local and global parameter name declarations are different for functions and methods. The first parameter in Swift 4 is referred by preposition named as 'with', 'for' and 'by' for easy to access naming conventions.

In Swift 4, you can declare first parameter name as local parameter and the remaining parameter names as global parameter names.

Let's see an example. Here 'no1' is declared as local parameter names and 'no2' is used for global declarations and accessed through out the program.




Self property in Methods

Methods have an implicit property called 'self' for all its defined type instances. 'Self' property or Self method is provided with methods to access the instance itself.



Result Inside Self Block: 300
Result Inside Self Block: 700
Result is: 280
Result is: 250
Result is: 680
Result is: 650

Modify Value Types from Instance Methods

In Swift 4, structures and enums belong to value types which cannot be altered by its instance methods but we can modify the value types by 'mutating' behavior. Mutate will make any changes in the instance methods and will return back to the original form after the execution of the method. Also, by the 'self' property new instance is created for its implicit function and will replace the existing method after its execution.




Next TopicSwift Subscripts

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA