swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.59k stars 10.36k forks source link

[SR-7524] Non-accurate ambiguity error #50066

Open swift-ci opened 6 years ago

swift-ci commented 6 years ago
Previous ID SR-7524
Radar None
Original Reporter gmosx (JIRA User)
Type Bug
Additional Detail from JIRA | | | |------------------|-----------------| |Votes | 0 | |Component/s | Compiler | |Labels | Bug | |Assignee | @xedin | |Priority | Medium | md5: 1ff3c4a77acedeb5a72b9815c51ccc1d

Issue Description:

Reproduction scenario:

extension Sequence where Element: Numeric {
    public func sum() -> Element {
        return reduce(0, +)
    }
}

extension Sequence {
    public func sum<T>() -> T where T: Numeric, Element == T? {
        var sum: T = 0

        for value in self {
            if let value = value {
                sum += value
            }
        }

        return sum
    }
}

extension DataSeries: BidirectionalCollection {
    public typealias Value = Any?
    public typealias Element = Value
    ...
}

let series: DataSeries

let s = series.sum()

yields the following not very helpful error:

*****:70:24: error: ambiguous reference to member 'sum()'
        XCTAssertEqual(series.sum(), 948.872)
                       ^~~~~~
Statistics.Sequence:2:17: note: found this candidate
    public func sum() -> Self.Element
                ^
Statistics.Sequence:2:17: note: found this candidate
    public func sum<T>() -> T where T : Numeric, Self.Element == T?

I suspect the real error is that series is a Sequence of Any? instead of Numeric?

For more context, please see this thread on forums.swift.org:

https://forums.swift.org/t/generic-method-over-a-sequence-of-optionals/12106

bc7072e8-7d37-4a38-8fee-cab463d443b7 commented 6 years ago

cc @jckarter

jckarter commented 6 years ago

@DougGregor, @rudkx, or @xedin would be a better judge of the intended behavior here. It seems like the extension `sum` ought to be more specific in this case, but is the type checker set up to score constrained generics in this way (or expected to be)?

xedin commented 6 years ago

I think my changes in https://github.com/apple/swift/pull/15946 are going to fix this case because first extension is supposed to be more specific than other one one with generic signature in `sum` method.