Swift:调用返回类型不明确的重载方法 [英] Swift: call overloaded method with ambiguous return type

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

问题描述

假设我有以下代码:

 公共类 A {}公共类 B : A {}公共类 Foo {public func bar() ->一种 {print("秘密隐藏方法")返回 A()}public func bar() ->乙{打印(易于访问的方法")返回 B()}}

问题是尝试调用它们会导致歧义.您可以调用 bar() ->BFoo().bar() 作为 B,但所有的 Foo().bar(), Foo().bar() 作为 A,并且 let a: A = Foo().bar() 产生 Ambiguous use of 'bar()' 编译器错误.>

底线:我如何调用 bar() ->A? 是否有一些棘手的语法?有必要反思吗?反射足够吗?

解决方案

编译器需要能够确定您想要执行 bar() 的哪个变体.您可以明确要执行的 func 类型,并利用柯里化来访问给定实例的正确实现.

let foo = Foo()让 a: ()->A = Foo.bar(foo)让 b: ()->B = Foo.bar(foo)一种()乙()

上面的代码会打印:

秘密隐藏方法易于访问的方法

Suppose I have the following code:

    public class A {}
    public class B : A {}
    public class Foo {
        public func bar() -> A {
            print("secret hidden method")
            return A()
        }

        public func bar() -> B {
            print("easily accessible method")
            return B()
        }
    }

The problem is try to call them leads to ambiguity. You can call bar() -> B with Foo().bar() as B, but all of Foo().bar(), Foo().bar() as A, and let a: A = Foo().bar() yield an Ambiguous use of 'bar()' compiler error.

Bottom line: How do I call bar() -> A? Is there some tricky syntax for it? Is reflection necessary? Is reflection sufficient?

解决方案

The compiler needs to be able to determine which variation of bar() you want to execute. You can be explicit about the type of func you want to execute, and take advantage of currying to access the correct implementation for a given instance.

let foo = Foo()
let a: ()->A = Foo.bar(foo)
let b: ()->B = Foo.bar(foo)
a()
b()

The above code will print:

secret hidden method
easily accessible method

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

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