O'Reilly logo

Cocoa Programming for OS X: The Big Nerd Ranch Guide by Aaron Hillegass, Adam Preble, Nate Chandler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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​ ​{​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required