[swift-users] Optionals and method overloading with Any

Joe Groff jgroff at apple.com
Wed Jan 6 21:25:18 CST 2016


> On Jan 6, 2016, at 7:16 PM, Don Wills via swift-users <swift-users at swift.org> wrote:
> 
> I really don't understand optionals.  This code fails with "Call can throw, but is not marked with try ..." on the program line:    t1.mth("abc", s1);
> 
> class Test {
> 	private var s1 : String!
> 
> 	func tst() {
> 		let t1 : Test1 = Test1()
> 		t1.mth("abc", s1)
> 	}
> }
> 
> class Test1 {
> 	func mth(p1 : String, _ p2 : String) -> String {
> 		return p1
> 	}
> 
> 	func mth(p1 : String, _ p2 : Any) throws -> String {
> 		return p1
> 	}
> }
> 
> but the program compiles fine if I change the code in either of these two manners:
> 
> 1. I define s1 as non-optional like this:  private var s1 = "", or
> 
> 2. I remove the second overloaded mth method (the one with "_ p2 : Any" as the second parameter and the throws clause)
> 
> Swift method lookup obviously chose the second mth func if it exists, but why?

Seems like a bug to me. I'd expect overload resolution to favor the (String, String) overload over the Any overload even if using an implicitly-unwrapped optional like this.

-Joe

> 
> 
> 
> 
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



More information about the swift-users mailing list