Skip to content

Instantly share code, notes, and snippets.

@devjangir
Last active June 13, 2017 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devjangir/af80ac6d2262938618baa197d7ac8d7b to your computer and use it in GitHub Desktop.
Save devjangir/af80ac6d2262938618baa197d7ac8d7b to your computer and use it in GitHub Desktop.
Working with Enums ( Add functions using Protocol )
// 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