Swift:方法重载只在返回类型上有所不同 [英] Swift: method overloads that only differ in return type

查看:135
本文介绍了Swift:方法重载只在返回类型上有所不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在看Swift类,其中定义了两种只返回类型不同的方法。我不习惯使用允许这种语言的语言(Java,C#等),所以我去寻找描述它如何在Swift中工作的文档。我在任何地方都找不到任何东西。我本来期望在Swift书中有关于它的整个部分。这在哪里记录了?

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?

这是我正在谈论的一个例子(我使用的是Swift 2,FWIW):

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"
    }
}

测试:

    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?

至于下标

语言参考/声明/下标声明


只要参数或返回类型与您的参数不同,您就可以在声明它的类型中重载下标声明。重新超载。

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.

语言指南/下标/下标选项


类或结构可以根据需要提供尽可能多的下标实现,并且将根据类型的值或包含的值推断要使用的相应下标。在下标括号内使用下标。

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博客中:

I cannot find any official docs about overloading methods or functions. but in the Swift Blog:

使用Swift REPL / Redefinition或Overload重新定义所有内容?


请记住,即使两个签名,Swift也允许函数重载只有它们的返回类型不同。

Keep in mind that Swift allows function overloading even when two signatures differ only in their return type.

这篇关于Swift:方法重载只在返回类型上有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆