Errors for operators

I was wondering if there's a particular reason to display different errors for wrongly applied operators.

struct AStruct {
    let value: Double
    
    static func + (lhs: Self, rhs: Self) -> Self {
        Self(value: lhs.value + rhs.value)
    }
}

let a = AStruct(value: 3)

print((1,2) + "p")
print(1 + "p")
print(a + "p")

In my opinion the second error, i.e.

Binary operator '+' cannot be applied to operands of type 'Int' and 'String'

is the most explicit and useful one, especially if you're dealing with custom structures/classes that conform to ExpressibleBy\w+Literal protocols. You immediately get which plus sign is affected and what types have been inferred.

2 Likes

On master compiler, I see the following diagnostics:

/Users/spare/Desktop/test.swift:10:14: error: binary operator '+' cannot be applied to operands of type '(Int, Int)' and 'String'
print((1, 2) + "p")
      ~~~~~~ ^ ~~~
/Users/spare/Desktop/test.swift:10:14: note: overloads for '+' exist with these partially matching parameter lists: (String, String)
print((1, 2) + "p")
             ^
/Users/spare/Desktop/test.swift:11:9: error: binary operator '+' cannot be applied to operands of type 'Int' and 'String'
print(1 + "p")
      ~ ^ ~~~
/Users/spare/Desktop/test.swift:11:9: note: overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)
print(1 + "p")
        ^
/Users/spare/Desktop/test.swift:12:9: error: operator function '+' requires that 'AStruct' conform to 'Sequence'
print(a + "")
        ^
Swift.RangeReplaceableCollection:3:35: note: where 'Other' = 'AStruct'
    @inlinable public static func + <Other>(lhs: Other, rhs: Self) -> Self where Other : Sequence, Self.Element == Other.Element

(P.S: It would be great if you post code snippets next time (instead of a screenshot) as it makes it really easy to copy-paste and run the code, instead of manually typing it out)

1 Like
Terms of Service

Privacy Policy

Cookie Policy