[swift-evolution] [Pitch] make == more restrictive at compile time

Gerd Castan Gerd at GerdCastan.de
Thu May 5 04:24:24 CDT 2016


Motivation:

The following code emits no compiler error in Swift 2.2:

import Foundation
func EQTest(lhs: NSArray, rhs: String) -> Bool {
    return (lhs == rhs)
}


I can imagine no use case where this code example makes sense, so I
would expect an error at compile time.

the function that makes this code valid is
@warn_unused_result
public func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool


Proposal:

find a way for the compiler to emit an error for the code example.


Discussion:

I can think of several ways to solve this:

1. remove "public func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool" from
the library
2. annotate "public func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool" so
that the compiler emits an error in the cate that there is no more
specific implementation.

I leave the way to implement this to a discussion since I'm not sure
which one (or some completely different approach) will lead to a
consistent language design.

I have the feeling that approach 2 is easier, better and gives more
control since it moves the responsibility for the error handling from
the compiler to the library where everybody (including the compiler) can
read it.

There might be more functions like "public func ==<T : Equatable>(lhs:
T?, rhs: T?) -> Bool" that lets the compiler accept nonsense tests for
equality for more specific cases. They should be handled in a similar
and consistent way if they exist.

This change is intended to let programers getting things done faster and
with less coding errors in Swift.


Gerd
https://github.com/GerdC






More information about the swift-evolution mailing list