Understanding how ambiguous operators are chosen fast

Here is a quick playground with two operator versions +:

protocol Value {
    func get() -> Float
}

func + (a:Value, b:Value) -> Float {
    print("Value.+")
    return a.get() + b.get()
}

func + (a:S, b:Value) -> Float {
    print("S.+")
    return a.get() + b.get()
}

struct S : Value {
    func get() -> Float {
        return 0
    }
}

struct T : Value {
    func get() -> Float {
        return 1
    }
}

let s1 = S()
let s2 = S()
let s3 = s1 + s2

let t1 = T()
let t2 = T()
let t3 = t1 + t2

When I start, I get the following output:

S.+
Value.+

I will correct that the fast compiler interprets Sas a more specific type than Value, and therefore it chooses S.+, and not Value.+for the first sum? Is this behavior set somewhere in official quick docs?

+4
source share

Source: https://habr.com/ru/post/1691265/


All Articles