Last active
June 13, 2017 11:59
-
-
Save devjangir/af80ac6d2262938618baa197d7ac8d7b to your computer and use it in GitHub Desktop.
Working with Enums ( Add functions using Protocol )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A Protocol that has update function to update Device State | |
protocol State { | |
// function is mutating so that Enum and structure can update the self | |
mutating func update() | |
} | |
// Enum wit Active and Inactive Device state | |
enum DeviceState : State { | |
case Active, Inactive | |
// Implement the update method to change device state | |
mutating func update() { | |
// check current device state and update | |
if self == .Inactive { | |
self = .Active | |
} else { | |
self = .Inactive | |
} | |
} | |
} | |
// creating object with Active state | |
var deviceState = DeviceState.Active | |
print(deviceState) // Output : Active | |
// call method on enum object to update state | |
deviceState.update() | |
print(deviceState) // Output : Inactive |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment