【问题标题】:How to change override function return type in Swift如何在 Swift 中更改覆盖函数返回类型
【发布时间】:2019-05-09 15:31:54
【问题描述】:
@objc public class A: NSObject
{
    public func getSomething() -> Something
    {
        return Something()
    }
}


@objc public class B: A{
    override public func getSomething() -> SomethingGood
    {
        return SomethingGood()
    }
}


@objc public class C: A{
    ...  
}

@objc public class Something: NSObject{
    var name: String=“”
}

@objc public class SomethingGood: Something{
    var type_id: Int = 0
}

Swift 编译器显示 B 类的覆盖函数的类型不兼容。如何实现上述内容?我曾尝试使用泛型,但一旦构建了库,它们就不适用​​于 Objective-C 开发人员。

我希望能够使用:

A.getSomething() 和 C.getSomething() 返回 Something 的对象

和 B.getSomething() 返回 SomethingGood 的对象。

而且我不想得到两个相同命名的函数,即 func getSomething() for B 具有两种不同的返回类型。

有什么想法吗?

代码用在一个用 Swift 编写的静态库中。编译库后,它应该对 swift 和 Objective-c 都可用。

【问题讨论】:

    标签: objective-c swift inheritance


    【解决方案1】:

    您不能更改返回类型,否则它不会是override。在这种情况下你仍然可以返回SomethingGood,只是你的函数声明不能​​显示返回类型。

    @objc public class B: A{
    override public func getSomething() -> Something
    {
        return SomethingGood()
    }
    
    // now whereever you're calling this, if you know it's SomethingGood, you can cast it
    if let somethingGood = b.getSomething() as? SomethingGood {
       // do something good
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 2013-04-01
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多