[swift-evolution] [pre-proposal] Automatic unwrapper boolean properties using unless keyword

David Waite david at alkaline-solutions.com
Thu Mar 31 18:14:48 CDT 2016


> On Mar 31, 2016, at 3:54 PM, Guilherme Torres Castro via swift-evolution <swift-evolution at swift.org> wrote:

> Example:
> if !myList?.isEmpty { print("Ok") }

Swift originally had Optionals be boolean evaluable. Unfortunately, nil does not always mean false, and assuming so by default can mask issues. I believe there may have also been an issue with types being promoted to optional and then evaluated as true.

One option here is to use a new custom prefix operator to indicate you desire optional == false behavior. I chose “??” in the code below:

prefix operator ?? {}

prefix func ??(arg:Bool?) -> Bool {
  return arg ?? false
}

let data:[String:Bool?] = ["nil": nil, "true": true, "false": false]

for (key, value) in data {
  if ??value {
    print(key)
  }
} # prints true

I don’t think a negated form is as clear, since this is a shortcut for two checks. However, I wrote one for completeness:

prefix operator ‽‽ {}
prefix func ‽‽(arg:Bool?) -> Bool {
  return !(arg ?? false)
}

-DW
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160331/a030d5e6/attachment.html>


More information about the swift-evolution mailing list