Swift Programmer, En Garde!

DZone 's Guide to

Swift Programmer, En Garde!

What should you do to diagnose which condition failed in a set of chained guard let statements?

· Mobile Zone ·
Free Resource

Here’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"]
        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
    .last ?? ""
  let outcome = "unwrap(\(unwrap ? "success" : "failure"))"
  print("\(source)(\(ref.line)), \(outcome), value: \(v)")
  return v

let dict: [String: Any] = ["Apple": "one", "Google": "two", "Microsoft": 3]
  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.urlSource.name }}