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 { 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:
struct Vector { ... var length: Double { return sqrt(x*x + y*y) } }
At other times it is useful to have a getter and setter for a computed property. This tends to be used to alias other properties or to transform a value before it is used elsewhere. For example, you could abstract the setting of the textField from the RandomPassword with a computed property:
class MainWindowController: NSWindowController { @IBOutlet weak var textField: NSTextField! var generatedPassword: String { set { textField.stringValue = newValue } get { return textField.stringValue } } ... @IBAction func generatePassword(sender: AnyObject) { let length = 8 generatedPassword = generateRandomString(length) } }
Computed properties do not have any storage associated with them. If you need to store a value, you must create a separate stored property for it.