Limiting a variable

You can also use property observers to limit the value of a variable. Say you had a light bulb that could only support a maximum current flowing through its filament.

struct LightBulb {

static let maxCurrent = 40 var current = 0 {

didSet {

if current > LightBulb.maxCurrent {

print("Current too high, falling back to previous setting.") current = oldValue

}

}

}

}

In this example, if the current flowing into the bulb exceeds the maximum value, it will revert to its last successful value. Notice there’s a helpful oldValue constant available in didSet so you can access the previous value.

Give it a try:

var light = LightBulb() light.current = 50

var current = light.current // 0 light.current = 40

current = light.current // 40

You try to set the lightbulb to 50 amps, but the bulb rejected that input. Pretty cool!

Note: Do not confuse property observers with getters and setters. A stored property can have a didSet and/or a willSet observer. A computed property has a getter and optionally a setter. These, even though the syntax is similar, are completely different concepts!

results matching ""

    No results matching ""