Swift Programmer, En Garde!
Swift Programmer, En Garde!
What should you do to diagnose which condition failed in a set of chained guard let statements?
Join the DZone community and get the full member experience.
Join For FreeHere’s a question for discussion that will bring shivers of shared pain to the Swift programmer, no doubt:
Sneaky Swift Tricks: The fake Boolean
Moshe Berman writes, “If I’ve got a bunch of chained guard let statements, how can I diagnose which condition failed, short of breaking apart my guard let into multiple statements? Given this example:
guard let keypath = dictionary["field"] as? String,
let rule = dictionary["rule"] as? String,
let comparator = FormFieldDisplayRuleComparator(rawValue: rule),
let value = dictionary["value"]
else
{
return nil
}
How can I tell which of the 4 let statements was the one that failed and invoked the else block?”
How, indeed? TL;DR There isn’t a really good way. Bah.
However, besides the linked article there’s an active discussion at the Stack Overflow question, and we’d suggest checking on them to see if anything that suits you has shown up, and if not pick up some more Swifty tricks along the way. The one we like the best so far is this gist from AfricanSwift defing the =∅ (null check) debug operator:
infix operator =∅ {}
func =∅<T> (v:T?, ref: (file: String, line: Int)) -> T? {
#if debug
var unwrap = false
if let _ = v { unwrap = true }
let source = ref.file
.characters
.split("/")
.map{String($0)}
.last ?? ""
let outcome = "unwrap(\(unwrap ? "success" : "failure"))"
print("\(source)(\(ref.line)), \(outcome), value: \(v)")
#endif
return v
}
let dict: [String: Any] = ["Apple": "one", "Google": "two", "Microsoft": 3]
guard
let apple = dict["Apple"] as? String =∅ (#file, #line),
let google = dict["Google"] as? String =∅ (#file, #line),
let microsoft = dict["Microsoft"] as? String =∅ (#file, #line)
else {
fatalError("unwrap failed")
}
print(apple, google, microsoft)
// Example output:
// playground218.swift(114), unwrap(success), value: Optional("one")
// playground218.swift(115), unwrap(success), value: Optional("two")
// playground218.swift(116), unwrap(failure), value: nil
Published at DZone with permission of Alex Curylo , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}