Modifying Value Types from Instance Methods
Structures and enumerations are value types in the Swift 4 language, meaning that instance methods cannot change them. Swift 4 language, on the other hand, offers flexibility to change the value types by “mutating” behaviour. After the instance methods have been executed, mutate will make any changes and then revert to the initial state. Additionally, a new instance is created for the implicit function by the “self” property, which replaces the current method after it has been used.
Swift
struct area { var length = 1 var breadth = 1 func area() -> Int { return length * breadth } mutating func scaleBy(res: Int ) { length *= res breadth *= res print (length) print (breadth) } } var val = area(length: 2, breadth: 4) val.scaleBy(res: 3) val.scaleBy(res: 30) val.scaleBy(res: 300) |
Output:
Swift – Methods
Methods are functions that belong to a specific type. Instance methods, which encapsulate particular tasks and functionality for working with an instance of a given type, can be defined by classes, structures, and enumerations. Type methods, which are connected to the type itself, can also be defined by classes, structures, and enumerations. In Objective-C, type methods are comparable to class methods.
Swift differs significantly from C and Objective-C in that structures and enumerations can define methods, whereas classes are the only types in Objective-C that can. In Swift, you can define a class, structure, or enumeration and still define methods on the type you create.
Contact Us