[swift-users] Optionals and method overloading with Any

Don Wills don.wills at portablesoftware.com
Wed Jan 6 21:16:52 CST 2016


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?

        






More information about the swift-users mailing list