I keep seeing Swift classes where two methods are defined that only differ in return type. I'm not used to working in languages where this is allowed (Java, C#, etc), so I went looking for the documentation that describes how this works in Swift. I've found absolutely nothing anywhere. I would have expected an entire section on it in the Swift book. Where is this documented?
Here is an example of what I'm talking about (I'm using Swift 2, FWIW):
class MyClass {
subscript(key: Int) -> Int {
return 1
}
subscript(key: Int) -> String {
return "hi"
}
func getSomething() -> Int {
return 2
}
func getSomething() -> String {
return "hey"
}
}
Test:
let obj = MyClass()
//let x = obj[99]
// Doesn't compile: "Multiple candidates fail to match based on result type"
let result1: String = obj[123]
print("result1 \(result1)") // prints "result1 hi"
let result2: Int = obj[123]
print("result2 \(result2)") // prints "result2 1"
//let x = obj.getSomething()
// Doesn't compile: "Ambiguous use of 'getSomething'"
let result3: String = obj.getSomething()
print("result3 \(result3)") // prints "result3 hey"
let result4: Int = obj.getSomething()
print("result4 \(result4)") // prints "result4 2"