这是我正在谈论的一个例子(我正在使用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" } }
测试:
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"
解决方法
Where is this documented?
至于下标:
Language Reference / Declarations / Subscript Declaration
You can overload a subscript declaration in the type in which it is declared,as long as the parameters or the return type differ from the one you’re overloading.
Language Guide / Subscripts / Subscript Options
A class or structure can provide as many subscript implementations as it needs,and the appropriate subscript to be used will be inferred based on the types of the value or values that are contained within the subscript braces at the point that the subscript is used.
我找不到任何关于重载方法或函数的官方文档.但在Swift博客中:
Redefining Everything with the Swift REPL / Redefinition or Overload?
Keep in mind that Swift allows function overloading even when two signatures differ only in their return type.