? suffix for <, >, <=, >= comparisons with optionals to prevent subtle bugs

I don’t have a problem with Optionals being comparable, but I do see the potential for bugs occurring as Swift automatically wraps values as Optionals when required. Not sure what the solution would be here, other than to make the wrapping of values explicit?

Here’s an example of when automatic Optional wrapping can cause unexpected results:

struct Pet {
  let age: Int
}

struct Person {
  let name: String
  let pet: Pet?
}

let peeps = [
  Person(name: "Fred", pet: Pet(age: 5)),
  Person(name: "Jill", pet: .None), // no pet here
  Person(name: "Burt", pet: Pet(age: 10)),
]

let ps = peeps.filter { $0.pet?.age < 6 }

ps == [Fred, Jill] // if you don’t own a pet, your non-existent pet is considered to be younger than any actual pet :dog:

If the Optional wrapping of ‘6’ in the comparison had to be explicit, then the result wouldn't be so unexpected.

Al

···

On 9 Dec 2015, at 11:31, Lucas Derraugh <lucas.derraugh@me.com> wrote:

This is related to a question I asked on SO a while back: option type - Swift nil has a numeric value? - Stack Overflow

Seems that many others have had confusion with the same problem, and it can sneak into your code without being aware of it. The simple case that I ran into was comparing an Optional Int to an Int. It is a very subtle bug and one that I don’t think should be allowed to occur. To me the intent isn't clear in this situation. I don’t think nil should be considered true or false if compared against. The only alternative I can think of is if comparing anything to a nil value, the result would be false; this would probably still lead to unexpected behavior though.

Lucas Derraugh
lucas.derraugh@me.com <mailto:lucas.derraugh@me.com>
607-793-3517

On December 9, 2015 at 6:10:40 AM, Al Skipp via swift-evolution (swift-evolution@swift.org <mailto:swift-evolution@swift.org>) wrote:

To me it seems logical that comparing Optional<Int> with Int (or another
Optional<Int>), if it's allowed at all, should return Optional<Bool>. Since
conditional statements only accept Bool, the user is forced to handle the
nil case explicitly.

I disagree that comparing Optional values should have a return value of Optional<Bool>.
If the following were to be true:

.None < .Some(0) == .None

Then logically, this would be too:

< [1,2,3] ==

I think most people would agree that the correct result to that comparison should be ‘true’, not .

When comparing ‘container’ types I think it’s important to have a simple Bool result, otherwise things get very peculiar (conceptually the Optional type is really just a container with a maximum count of 1).
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org <mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution