Treehouse Intermediate Course Part 6 (Type Methods and Final Classes)
Here we go! Just a little bit more today - which is best - little and often! Last time it was semantics for value and reference types. I'm starting with Type Methods....
Type Methods
Before we used the keyword 'static' for properties, computed ones I believe.
Type Methods
Before we used the keyword 'static' for properties, computed ones I believe.
struct Point {
let x: Double
let y: Double
}
struct Map {
static let origin = Point(x: 0, y: 0)
static func distance(to point: Point) -> Double {
let horizontalDistance = origin.x - point.x
let verticalDistance = origin.y - point.y
func square(_ value: Double) -> Double {
return value * value
}
let horizontalDistanceSquare = square(horizontalDistance)
let verticalDistanceSquare = square(verticalDistance)
return sqrt(verticalDistanceSquare + horizontalDistanceSquare)
}
}
So a couple of things to recap there. First off, static means you can access the property/function within the type but NOT an instance.
Secondly, the 'distance' method is a type method - as shown by the static keyword. The square function is a nested one - used only within the scope of the Map struct.
Final Classes
Inheritance adds a few additional requirements.
class Calculator {
class func squareRoot(_ value: Double) -> Double {
return sqrt(value)
}
}
Right so I THINK this means that a subclass will not inherit the func as per class keyword...
NO it's not that!
let calculator1 = Calculator()
calculator1.squareRoot(4)
Right got it. Basically you cannot use the func on an instance - just on the type itself. The example above returns an error.
You can use the override keyword in a sub class. Dynamically dispatched is what Pasan said! override class func.
You can also use the 'final' keyword. This means you CANNOT override it in any way! Makes sense. final class func.
You can mark classes, instance methods as final too.
So just a quick one today but have learned some useful stuff. More tomorrow!
Comments
Post a Comment