Created
June 27, 2014 22:53
-
-
Save bgrace/b8928792760159ca58a1 to your computer and use it in GitHub Desktop.
Response to http://stackoverflow.com/questions/24459171/swift-switch-statement-on-a-tuple-of-optional-booleans
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
var dict = Dictionary<String,Bool>() | |
dict["a"] = true | |
dict["c"] = false | |
func matchOneOrTheOtherWithOptionals(a: Bool?, b: Bool?) -> String { | |
switch (a, b) { | |
case (.Some(true), let b) where b == .None || !b!: | |
return "a was true, but b was None or false" | |
case (let a, .Some(true)) where a == .None || a == .Some(false): | |
return "a was None or false and b was true" | |
default: | |
return "They both had a value, or they were both missing a value" | |
} | |
} | |
matchOneOrTheOtherWithOptionals(true, .None) | |
matchOneOrTheOtherWithOptionals(true, false) | |
matchOneOrTheOtherWithOptionals(.None, true) | |
matchOneOrTheOtherWithOptionals(false, true) | |
matchOneOrTheOtherWithOptionals(false, false) | |
matchOneOrTheOtherWithOptionals(true, true) | |
matchOneOrTheOtherWithOptionals(.None, .None) | |
func noneToFalse(bool: Bool?) -> Bool { | |
if let b = bool { | |
return b | |
} else { | |
return false | |
} | |
} | |
func matchOneOrTheOther(a: Bool, b: Bool) -> String { | |
switch (a, b) { | |
case (true, false): | |
return "a is true, b was false or None" | |
case (false, true): | |
return "a was false/None, b was true" | |
default: | |
return "both were true, or both were false/None" | |
} | |
} | |
matchOneOrTheOther(noneToFalse(dict["a"]), noneToFalse(dict["b"])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment