[swift-users] Overload by return type optionality?

Mark Lacey mark.lacey at apple.com
Thu Oct 13 22:00:50 CDT 2016


> On Oct 13, 2016, at 5:37 PM, Hooman Mehr via swift-users <swift-users at swift.org> wrote:
> 
> 
>> On Oct 13, 2016, at 3:31 PM, Rick Mann via swift-users <swift-users at swift.org <mailto:swift-users at swift.org>> wrote:
>> 
>> Would it make sense to be able to specify priority for a set of overloaded methods to help resolve ambiguity?

I don’t think we want to head down that route, partially because using a contextual type as mentioned below removes the ambiguity.

> This might be pretty useful in some situations, but I am not sure if the semantic complexity that it introduces is worth it.
> 
> Another example of how this could be useful: 
> 
> I made a bare-bones rational number type <https://gist.github.com/hooman/6e08c48e1e06ee19e06e5b09f664f9be> for Swift a while ago. I would love to be able to overload “/“ operator to create fractions (rational numbers) instead of dividing two integers. 
> 
> If I overloaded “/“ to return rational (Int / Int -> Rational), the result type of the operator would become ambiguous for every use of it with integer operands.

That isn’t the way the type checker works. If you use an explicit type to contextualize the expression, there is no ambiguity. For example this works without any ambiguity.

struct Rational {}
func / (lhs: Int, rhs: Int) -> Rational { return Rational() }
func + (lhs: Rational, rhs: Rational) -> Rational { return Rational() }

func use(r: Rational) {}

let x: Rational = (1 / 2) + (2 / 3)  // Rational result type, no ambiguity
use(r: (1 / 2) + (2 / 3))  // Rational argument type, no ambiguity
let y = (1 / 2) as Rational    // Calls func/(Int,Int)->Rational

Mark

> It would be nice if I could prioritize my overload of “/“ over stdlib definition to resolve the ambiguity. 
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161013/3dd70da4/attachment.html>


More information about the swift-users mailing list