Skip to content

Instantly share code, notes, and snippets.

@benvium
Last active August 29, 2015 14:05
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 benvium/cb8fb6411cd670fffb02 to your computer and use it in GitHub Desktop.
Save benvium/cb8fb6411cd670fffb02 to your computer and use it in GitHub Desktop.
Apple Swift: String enums, switch ranges, Printable protocol (description property)
// 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