gpt4 book ai didi

ios - 动态(通用)快速继承自

转载 作者:行者123 更新时间:2023-11-28 07:03:37 26 4
gpt4 key购买 nike

我没有找到任何解决方案,很可能这是不可能的,但我会试一试(如果不可能,我很乐意得到一个简短的解释原因)。

我正在尝试在 Swift 中创建一个类,我们称它为 Foo,我希望 FooChild 继承自 Foo。到目前为止,没有问题。问题是,我希望 Foo 动态继承“任何类”,也许是泛型。

有点像

class Foo<T> : <T>{

}

class FooChild : Foo<NSObject> {

}

class FooChild2 : Foo<UIview> {

}

我希望 FooChild 和 FooChild2 都继承自 Foo,但我希望 foo 一次继承自 NSObject,一次继承自 UIView(示例中使用了随机类)。

这可能吗?即使在我会以某种方式桥接的 Objective-C 代码中。

最佳答案

swift 1.2

不,那是不可能的。

你可以做的是:

protocol Foo { }

class FooChild1: NSObject, Foo { }

class FooChild2: UIView, Foo { }

swift 2

是的,现在这是可能的。

Non-generic classes may inherit from generic classes. (15520519)

参见:Xcode 7 Beta Release Notes ,“Swift 2.0 和 Objective-C 的新特性”一章,“Swift 语言特性”部分

例如以下是可能的:

import UIKit

class Foo<T> { }

class FooChild: Foo<NSObject> { }

class FooChild2: Foo<UIView> { }

let fooChild = FooChild()

let fooChild2 = FooChild2()

此外,在 Swift 2 中,如果您需要 Swift 1.2 示例中的协议(protocol) Foo 来提供一些默认行为,您可以使用默认协议(protocol)实现。

You can use protocol extensions to provide a default implementation to any method or property requirement of that protocol. If a conforming type provides its own implementation of a required method or property, that implementation will be used instead of the one provided by the extension.

参见:The Swift Programming Language , “协议(protocol)”一章,“提供默认实现”一节

关于ios - 动态(通用)快速继承自 <T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31405363/

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