Swift - Custom Type Class Properties

Introduction

Classes can have properties.

In Swift, there are two types of properties:

  • Stored property: a constant or variable that is stored within an instance of a class or a structure. When you declare a variable or constant within a class or structure, that is a stored property.
  • Computed property: calculate values and typically return values.

Classes store their data in properties.

Properties are variables or constants that are attached to instances of classes.

Properties that you've added to a class are usually accessed like this:

class Counter { 
    var number: Int = 0 
} 
let myCounter = Counter() 
myCounter.number = 2 

The most basic type of properties are stored properties.

Stored properties are what you have when the variable is a value stored in the object, such as the number property on the Counter class.

You don't have to give your stored properties a value when you declare them.

All nonoptional stored properties must have a value at the end of the designated initializer.

Demo

class Counter { 
    var number  : Int 
    var optionalNumber  : Int? 

    init(value: Int) { 
        number = value /*from   w  w w .j  a  v  a 2 s  . c om*/
        // self.number now has a value 
        // self.optionalNumber does not 
    } 
} 
var anotherCounter = Counter(value:3) 
print(anotherCounter.number)

Result

Related Topics