Last active
August 29, 2015 14:21
-
-
Save hborders/316123ce2e506b9f11bc to your computer and use it in GitHub Desktop.
Swift enums with labels
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
enum Foo { | |
// enums can have many values, and they can be labeled | |
case Bar( | |
barString: String, | |
barInt: Int) | |
// or unlabeled | |
case Baz( | |
String, | |
Int) | |
} | |
// you must now use a label when creating a Foo.Bar | |
let barFoo = Foo.Bar( | |
barString: "barString", | |
barInt: 32) | |
switch barFoo { | |
case .Bar( | |
let barString, | |
let barInt): | |
// you don't need to label your variables when you capture them in a switch/case statement | |
print("barString: \(barString), barInt: \(barInt)") | |
case .Baz(let bazTuple): | |
// you can capture multiple values as a single tuple | |
print("bazString: \(bazTuple.0), bazInt: \(bazTuple.1)") | |
} | |
// Foo.Baz still doesn't need a label | |
let bazFoo = Foo.Baz( | |
"bazString", | |
64) | |
switch bazFoo { | |
// you can label your variables when you capture them in a switch/case statement if you want | |
// they don't do anything, they exist only for clarity. | |
case .Bar( | |
barString: let myBarString, | |
barInt: let myBarInt): | |
print("barString: \(myBarString), barInt: \(myBarInt)") | |
// the usual way to capture variables in a switch/case statement | |
case .Baz( | |
let bazString, | |
let bazInt): | |
print("bazString: \(bazString), bazInt: \(bazInt)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment