简体   繁体   English

Swift泛型类类型都是子类并且符合协议

[英]Swift generic class type both subclass and conforms to protocol

I'm trying to write a generic class in Swift who's generic type both inherits from a class and conforms to a protocol. 我正在尝试在Swift中编写泛型类,它的泛型类型都从类继承并符合协议。 However, the following code results in a compiler crash with Segmentation fault: 11. 但是,以下代码会导致编译器因Segmentation fault而崩溃:11。

protocol Protocol {
    var protocolProperty: Any? { get }
}

class Class {
    var classProperty: Any?
}

class GenericClass<T: Class where T: Protocol> {

    var genericProperty: T?

    func foo() {
        let classProperty: Any? = genericProperty!.classProperty
        // This is the culprit
        let protocolProperty: Any? = genericProperty!.protocolProperty
    }

}

Commenting out the access to the protocol property allows the program to compile. 注释掉对协议属性的访问允许程序编译。 There is no way to access anything from the protocol without the compiler crashing. 在没有编译器崩溃的情况下,无法从协议访问任何内容。 Is there a workaround to creating a generic class that works like this? 是否有一种解决方法来创建一个像这样工作的泛型类?

As MikeS notes, you should open a radar for the crash. 正如MikeS所说,你应该为坠机打开雷达。 It should never crash. 它永远不会崩溃。

But the solution is to focus on what protocol (ie list of methods) you actually need T to conform to rather than getting wrapped up in the class. 但解决方案是专注于你真正需要T符合的协议(即方法列表),而不是在课堂上被包裹起来。 For instance: 例如:

protocol WhatGenericClassHolds : Protocol {
  var classProperty: Any? { get }
}

class GenericClass<T: WhatGenericClassHolds> { ... }

There is a problem in your declaration. 您的声明中存在问题。 conform your class to the protocol as below 使您的班级符合以下协议

protocol A {
    var somePropertyInt : Int? {get }
}

class B:A {
    var someProperty : String? 
    var somePropertyInt:Int?;
}


class GenericClass<T: B where T: A  > {
    var someGenericProperty : T?

    func foo() {
         println(someGenericProperty!.someProperty)
         println(someGenericProperty!.somePropertyInt)   
    }
}


var someGen = GenericClass()

 someGen.someGenericProperty?.somePropertyInt
 someGen.someGenericProperty?.someProperty

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM