简体   繁体   中英

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. However, the following code results in a compiler crash with 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. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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