Skip to content

Instantly share code, notes, and snippets.

@nsswifter
Created December 25, 2023 10:39
Show Gist options
  • Save nsswifter/488b62537517af105e4922e8d699cf67 to your computer and use it in GitHub Desktop.
Save nsswifter/488b62537517af105e4922e8d699cf67 to your computer and use it in GitHub Desktop.
Swift Challenge: Cool Ways to Evaluate Two Bool Variables and Return a Result
// I have two bool variables. and I want to write a method with this logic:
// if two variables are true return .both
// and if first variable is true return .first
// and if the second one is true return .second
// otherwise return .none
enum Result {
case first
case second
case both
case none
}
let first = true
let second = false
// First Approach, with `switch` expression introduced in Swift V 5.9
func evaluateVariables1(_ first: Bool, _ second: Bool) -> Result {
switch (first, second) {
case (true, true):
.both
case (true, false):
.first
case (false, true):
.second
case (false, false):
.none
}
}
print(evaluateVariables1(first, second))
// Second Approach, with ternary operator
func evaluateVariables2(_ first: Bool, _ second: Bool) -> Result {
first && second ? .both :
first ? .first :
second ? .second :
.none
}
print(evaluateVariables2(first, second))
// Third Approach, with Swift Tuple and Closure way
func evaluateVariables3(_ first: Bool, _ second: Bool) -> Result {
[(first && second, Result.both),
(first, .first),
(second, .second)
].first { $0.0 }?.1 ?? .none
}
print(evaluateVariables3(first, second))
// Forth Approach, with `if` expression introduced in Swift V 5.9
func evaluateVariables4(_ first: Bool, _ second: Bool) -> Result {
if first, second { Result.both } else {
if first { .first } else {
if second { .second } else {
.none
}
}
}
}
print(evaluateVariables4(first, second))
// Fifth Approach, Kinda functional way (using Swift Closures)
func evaluateVariables5(_ first: Bool, _ second: Bool) -> Result {
{ first ? .first : { second ? .second : { first && second ? .both : .none }() }() } ()
}
print(evaluateVariables5(first, second))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment