Skip to content

Instantly share code, notes, and snippets.

@hborders
Last active August 29, 2015 14:21
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 hborders/316123ce2e506b9f11bc to your computer and use it in GitHub Desktop.
Save hborders/316123ce2e506b9f11bc to your computer and use it in GitHub Desktop.
Swift enums with labels
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