ios – Swift:方法重载只在返回类型上有所不同

前端之家收集整理的这篇文章主要介绍了ios – Swift:方法重载只在返回类型上有所不同前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在看 Swift类,其中定义了两种方法,它们的返回类型不同.我不习惯使用允许这种语言的语言(Java,C#等),所以我去寻找描述它如何在Swift中工作的文档.我在任何地方都找不到任何东西.我本来期望在Swift书中有关于它的整个部分.这记录在哪里?

这是我正在谈论的一个例子(我正在使用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.

原文链接:https://www.f2er.com/iOS/330752.html

猜你在找的iOS相关文章