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

编程入门 行业动态 更新时间:2024-10-13 06:19:45
本文介绍了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:方法重载只在返回类型上有所不同

本文发布于:2023-07-19 08:43:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1154817.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有所不同   只在   类型   方法   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!