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

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

概述我一直在看 Swift类,其中定义了两种方法,它们的返回类型不同.我不习惯使用允许这种语言的语言(Java,C#等),所以我去寻找描述它如何在Swift中工作的文档.我在任何地方都找不到任何东西.我本来期望在Swift书中有关于它的整个部分.这记录在哪里? 这是我正在谈论的一个例子(我正在使用Swift 2,FWIW): class MyClass { subscript(key: Int 我一直在看 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.

总结

以上是内存溢出为你收集整理的ios – Swift:方法重载只在返回类型上有所不同全部内容,希望文章能够帮你解决ios – Swift:方法重载只在返回类型上有所不同所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1098344.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存