Computed Properties
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 { ...
Get Cocoa Programming for OS X: The Big Nerd Ranch Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.