Swift - Custom Type Typed Properties

Introduction

Instance properties belong to an instance of a particular type.

Type properties belongs to a class.

Typed properties are commonly known as static properties or class properties in other programming languages such as Java, C#, and Objective-C.

Typed properties are accessed using the class name.

Consider the following example:


class Point {
     var x = 0.0
     var y = 0.0
     let width = 2
     lazy var pointMath = PointMath()

     class var origin:(Double, Double) {
          get {
              return (0,0)
          }
     }

     var newPosition:(Double, Double) {
         get {
             return  (x, y)
         }
         set (position) {    //position is a tuple
             x = position.0  //x
             y = position.1  //y
         }
     }
}

For classes, only computed type properties are supported.

For structures, both stored and computed type properties are supported.

For structures, you use the static keyword instead of the class keyword to denote a typed property.

Here, origin is a typed property-it is prefixed with the class keyword.

To access the typed property, use its class name and call it directly:

print(Point.origin )    //(0.0, 0.0)

Related Topic