April 2015
Intermediate to advanced
556 pages
17h 47m
English
It is frequently useful to find a vector’s length or magnitude. You could do this by adding a function returning a Double:
struct Vector {
...
func length() -> Double {
return sqrt(x*x + y*y)
}
}
However, it is much more natural to think of this as a read-only property. In Swift the general term for this is computed property, which is in contrast to the stored properties you have been using so far. A read-only computed property version of length would look like this:
struct Vector {
...
var length: Double {
get {
return sqrt(x*x + y*y)
}
}
}
This read-only computed property pattern (called a “getter”) is so common, in fact, that Swift provides a shorthand means of expressing it. Add this to Vector:
Read now
Unlock full access