Swift switch statement on a tuple of optional booleans -


i'm having trouble figuring out how use optionals inside tuple inside switch. below .some(let ...) ... syntax works non-tuple, inside tuple expected separator stuff :(

var dict = dictionary<string,bool>() dict["a"] = true  switch (dict["a"],dict["b") { case (.some(let a) !a, .some(let b) b):   println("false/nil, true") case (.some(let a) a, .some(let b) !b):   println("true, false/nil") 

i want avoid doing following

    if let = self.beaconlist["a"] {         if let b = self.beaconlist["b"] {             // a, b         } else {             // a, !b         }     } else {         if let b = self.beaconlist["b"] {             // !a, b         } else {             // !a, !b         }     } 

there bunch of ways this, fix syntax of trying literally, need explicitly unbox optional, either matching against .some(false), or unwrapping ! (which think kind of weird, you'll see)

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) b == .none || !b!: // gross         return "a true, b none or false"     case (let a, .some(true)) == .none || == .some(false):         return "a none or false , b true"     default:         return "they both had value, or both missing value"     } }  matchoneortheotherwithoptionals(true, .none) // "a true, b none or false" matchoneortheotherwithoptionals(true, false) // "a true, b none or false" matchoneortheotherwithoptionals(.none, true) // "a none or false , b true" matchoneortheotherwithoptionals(false, true) // "a none or false , b true"  matchoneortheotherwithoptionals(false, false) // "they both had value, or both missing value" matchoneortheotherwithoptionals(true, true) // "they both had value, or both missing value" matchoneortheotherwithoptionals(.none, .none) // "they both had value, or both missing value" 

you try following:

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 true, b false or none"     case (false, true):         return "a false/none, b true"     default:         return "both true, or both false/none"     } }  matchoneortheother(nonetofalse(dict["a"]), nonetofalse(dict["b"])) 

here's gist of playground used while writing answer: https://gist.github.com/bgrace/b8928792760159ca58a1


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -