【问题标题】:Swift generic class type both subclass and conforms to protocolSwift 泛型类类型既是子类又符合协议
【发布时间】:2014-09-26 04:56:22
【问题描述】:

我正在尝试用 Swift 编写一个泛型类,它的泛型类型既继承自类又符合协议。但是,以下代码会导致编译器崩溃并出现分段错误: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
    }

}

注释掉对协议属性的访问允许程序编译。如果编译器崩溃,就无法从协议中访问任何内容。有没有一种解决方法来创建一个像这样工作的泛型类?

【问题讨论】:

  • 无论代码如何,编译器都不应崩溃。如果你还没有,你应该报告给苹果(bugreport.apple.com)。

标签: xcode swift


【解决方案1】:

正如 MikeS 所说,您应该为崩溃打开一个雷达。它永远不会崩溃。

但解决方案是关注您实际需要T 遵守的协议(即方法列表),而不是被包裹在类中。例如:

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

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

【讨论】:

    【解决方案2】:

    您的声明有问题。使您的课程符合以下协议

    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
    

    【讨论】:

      猜你喜欢
      • 2014-12-09
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      相关资源
      最近更新 更多