gpt4 book ai didi

objective-c - 如何在 Swift 中更改覆盖函数返回类型

转载 作者:行者123 更新时间:2023-11-28 09:48:52 29 4
gpt4 key购买 nike

@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。

最佳答案

您不能更改返回类型,否则它不会是覆盖。在这种情况下,您仍然可以返回 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
}

关于objective-c - 如何在 Swift 中更改覆盖函数返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53676766/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com