简体   繁体   English

如何在Swift中构造通用类型协议一致性?

[英]How do you structure generic type protocol conformance in Swift?

The following contrived Swift 2 example from real-world code won't compile: 以下来自真实代码的人为的Swift 2示例将无法编译:

protocol SomeModelType {  }

protocol SomeProtocol {
    var someVar: SomeModelType? { get }
}

class ConcreteClass<T: SomeModelType>: SomeProtocol {
    var someVar: T?
}

This doesn't make sense to me fully. 这对我来说完全没有意义。 I would assume in ConcreteClass that because I have T being constrained to SomeModelType and have T as the backing type for the someVar property, the compiler would be able to figure out that the SomeProtocol was being conformed to by ConcreteClass . 我会在ConcreteClass中假设,因为我将T约束为SomeModelType并且将T作为someVar属性的后备类型,所以编译器将能够确定SomeProtocol是否符合ConcreteClass

How should an example like this be structured? 这样的例子应该如何构成? Is it possible to the Swift compiler to determine protocol conformance through generic type constraints? Swift编译器是否可以通过通用类型约束确定协议一致性?

protocol SomeModelType {  }

protocol SomeProtocol {

    associatedtype T: Any
    var someVar: T? { get }
}

class ConcreteClass<T> :SomeProtocol where T: SomeModelType {

    var someVar: T?

}

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

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