Friday, 13 December 2019

Swift Chapter 12 - methods


methods are functions.
classes , structures and enumerations all can have methods.

####Instance Methods
Local and External Parameter Names for Methods:(Local parameter is argument name and external name is in obj-c and swift . external name is wording used before the local param name.)

Ex:
class Counter {
var count: Int = 0
func incrementBy(amount: Int, numberOfTimes: Int) {
count += amount * numberOfTimes
}
}
let counter = Counter()
counter.incrementBy(5, numberOfTimes: 3) ;// here numberOfTimes is used as external name. Swift treats amount as a local name only, but treats numberOfTimes as both a local and an external name. You don’t need to define an external parameter name for the first argument value, because its purpose is clear from the function name incrementBy(_:numberOfTimes:). you can provide external
name to first parameter too. if you do not want to provide an external name for the second or subsequent parameter, use underscore character (_) as an explicit external parameter
name for that parameter.

Modifying Value Types (struct , enum) from Within Instance Methods:
no self for value type. if u want to modify the value type from within instance method use mutating behavior for that method.
Ex.
struct Point {
var x = 0.0, y = 0.0
mutating func moveByX(deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
;// above can be written as self = Point(x: x + deltaX, y: y + deltaY) Assigning
to self Within a Mutating Method
}
}

You can not call mutating method on const struct.

####Type Methods (static method)
Classes may also use the class keyword to allow subclasses to override the superclass’s implementation of that method.
class SomeClass {
class func someTypeMethod() {
// type method implementation goes here
}
}


0 comments:

Post a Comment

Search This Blog

Powered by Blogger.

Blog Archive