Skip to content

Instantly share code, notes, and snippets.

@zachwaugh
Last active February 6, 2023 16:15
Show Gist options
  • Save zachwaugh/b4574c0ad8982f848e51 to your computer and use it in GitHub Desktop.
Save zachwaugh/b4574c0ad8982f848e51 to your computer and use it in GitHub Desktop.
Swift shortcut for returning and/or assigning the result of switch statement?
// Can currently do this
func titleForSection1(section: Int) -> String? {
switch section {
case 0: return "Foo"
case 1: return "Bar"
default: return nil
}
}
// But I want to do this to remove the redundant returns
func titleForSection2(section: Int) -> String? {
switch section {
case 0: "Foo"
case 1: "Bar"
default: nil
}
}
// This would be fine too
func titleForSection2(section: Int) -> String? {
let title = switch section {
case 0: "Foo"
case 1: "Bar"
default: nil
}
return title
}
// Or this if it worked
func titleForSection2(section: Int) -> String? {
let title = {
switch section {
case 0: "Foo"
case 1: "Bar"
default: nil
}
}()
return title
}
// @jspahrsummers points out this works for more convenient assignment
func titleForSection2(section: Int) -> String? {
let title = {
switch section {
case 0: return "Foo"
case 1: return "Bar"
default: return nil
}
}()
return title
}
@VaslD
Copy link

VaslD commented Dec 25, 2020

Came across the need to assign and return according to enum values recently.

Someone should propose a switch expression equivalent on Swift Evolution. Basically it enables:

// If implemented in Swift syntax:

return section switch {
  0 => "Foo"
  1 => "Bar"
  default => nil
}

Or when doing assignments:

let title = section switch {
  0 => "Foo"
  1 => "Bar"
  default => nil
}

@Pash237
Copy link

Pash237 commented Feb 6, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment