Last active
February 6, 2023 16:15
-
-
Save zachwaugh/b4574c0ad8982f848e51 to your computer and use it in GitHub Desktop.
Swift shortcut for returning and/or assigning the result of switch statement?
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
// 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 | |
} |
Swift evolution accepted: https://github.com/apple/swift-evolution/blob/main/proposals/0380-if-switch-expressions.md
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:Or when doing assignments: