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:

s​t​r​u​c​t​ ​V​e​c​t​o​r​ ​{​
 ​ ​ ​ ​.​.​.​

 ​ ​ ​ ​f​u​n​c​ ​l​e​n​g​t​h​(​)​ ​-​>​ ​D​o​u​b​l​e​ ​{​
 ​ ​ ​ ​ ​ ​ ​ ​r​e​t​u​r​n​ ​s​q​r​t​(​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:

s​t​r​u​c​t​ ​V​e​c​t​o​r​ ​{​ ​ ​ ​ ​.​.​.​ ​ ​ ​ ​v​a​r​ ​l​e​n​g​t​h​:​ ​D​o​u​b​l​e​ ​{​ ​ ​ ​ ​ ​ ​ ​ ​g​e​t​ ​{​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ...

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.