Type scope operators doesn't work if type is declared in function scope, bug?

(I've only tested this in Xcode 10 b6)

This program compiles and works as expected:

struct S {
    var v: Int
    static func +(lhs: S, rhs: S) -> S { return S(v: lhs.v + rhs.v) }
}
func foo() {
    print(S(v: 123) + S(v: 456)) // 579
}
foo()

But this program produces an unexpected compile time error:

func foo() {
    struct S {
        var v: Int
        static func +(lhs: S, rhs: S) -> S { return S(v: lhs.v + rhs.v) }
    }
    print(S(v: 123) + S(v: 456)) // ERROR: Binary operator '+' cannot be applied to two 'S' operands
}
foo()

Is this a bug (ie should the second program compile) or bad diagnostics?


Another example:

struct S : Equatable {
    var v: (Int, Int)
    static func ==(lhs: S, rhs: S) -> Bool { return lhs.v == rhs.v }
}
func foo() {
    print(S(v: (1, 2)) == S(v: (1, 2))) // true
}
foo()

But:

func foo() {
    struct S : Equatable { // ERROR: Type 'S' does not conform to protocol 'Equatable'
        var v: (Int, Int)
        static func ==(lhs: S, rhs: S) -> Bool { return lhs.v == rhs.v }
    }
    print(S(v: (1, 2)) == S(v: (1, 2)))
}
foo()

Hi Jens, the conformance thing came up just yesterday. I wouldn't be surprised if your first issue is related. Feel free to add your example here: SR-8696

Thanks!

I added a comment to that bug and SR-8672 which I linked as related.

Seems to me like the seemingly protocol-related issues described in the following threads are caused by the simpler (non-protocol related) issue of type scope operators not working when the type is declared in function scope:

1 Like