Last active
August 29, 2015 14:05
-
-
Save benvium/cb8fb6411cd670fffb02 to your computer and use it in GitHub Desktop.
Apple Swift: String enums, switch ranges, Printable protocol (description property)
This file contains 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
// Playground - noun: a place where people can play | |
import UIKit | |
enum State : String { | |
case ASLEEP = "asleep", | |
AWAKE = "awake", | |
DRUNK = "drunk" | |
} | |
// Printable means there's a 'description' property | |
class Person : Printable { | |
init(name:String) { | |
self.name = name; | |
} | |
// Computed property - this forms a get | |
var status: State { | |
let num = rand() % 10; | |
switch num { | |
case 0..<3: | |
return State.ASLEEP | |
case 3..<6: | |
return State.AWAKE | |
default: | |
return State.DRUNK | |
} | |
} | |
var description: String { | |
// toRaw is required for it to print the String value (e.g. 'awake'). Otherwise it prints (Enum Value) unhelpfully! | |
return "\(name) is \(status.toRaw())" | |
} | |
var name:String; | |
} | |
var states = ""; | |
// repeat 10 times. toRaw gives us the String value of the enum | |
for i in 0..<10 { | |
let name = "Person"+String(format: "%02d", i) | |
states += " \(Person(name:name).description) " | |
// Note: shouldn't need to call description here (i think) but Playgrounds needs us to | |
} | |
println(states); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment