Jens
September 5, 2018, 7:54am
1
(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
Jens
September 5, 2018, 12:56pm
3
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:
why does this not work when the struct is local to a function?
func f()
{
struct Pair:Hashable, Comparable
{
let x:Int, y:Int
static
func < (lhs:Pair, rhs:Pair) -> Bool
{
if lhs.y < rhs.y
{
return true
}
else if lhs.y == rhs.y
{
return lhs.x < rhs.x
}
else
{
return false
}
}
…
Hello ! I would like to have some clarifications about why Set does not interact properly with a Hashable struct declared in a function.
Here I have a struct Hello that conforms to hashable and only needs its id for the hashValue. Because structs need to have Equatable custom conformance to have custom hash behavior, so a == function is declared. 23
I first declare a Set with an identifier 123 and the I try to insert another struct having the same identifier with different "value". It does not…
1 Like