简体   繁体   English

以通用协议作为返回类型的调用函数

[英]Calling function with generic protocol as return type

The following example should create concrete objects for abstract protocols. 以下示例应为抽象协议创建具体对象。

class ClassA<T: FloatingPointType> {}

protocol ProtocolA
{
    typealias T: FloatingPointType
    var value : ClassA<T>? { get set }
}

class ClassImplProtocolA<T: FloatingPointType> : ProtocolA
{
    var value : ClassA<T>? {
        get {
            return nil
        }
        set {
        }
    }
}

class Factory
{
    class func createProtocol<PA: ProtocolA where PA.T: FloatingPointType>() -> PA
    {
        let concreteObject = ClassImplProtocolA<PA.T>()
        let abstractObject = concreteObject as? PA
        return abstractObject!
    }
}

Now two questions: Is it possible to avoid the as? PA 现在有两个问题:是否可以避免as? PA as? PA ? as? PA and how does the syntax look like to call Factory.createProtocol<...>() ? 以及语法如何调用Factory.createProtocol<...>()

Or how do I work around this? 或者我该如何解决? All I want is an object of the abstract type PrtocolA<FloatingPointType> without exposing ClassImplProtocolA . 我想要的只是一个抽象类型PrtocolA<FloatingPointType>的对象,而没有暴露ClassImplProtocolA

First you cannot avoid as? PA 首先你不能避免as? PA as? PA since the return Type is determined by the type inference like this: as? PA因为返回类型由类型推断确定,如下所示:

let prot: ClassImplProtocolA<Double> = Factory.createProtocol()
let prot = Factory.createProtocol() as ClassImplProtocolA<Double>

Another issue in this case is that you cannot use FloatingPointType as generic type (has Self requirements) and you have to use one which conforms to this protocol (like Double and Float ). 这种情况下的另一个问题是,您不能将FloatingPointType用作通用类型(具有Self要求),而必须使用符合该协议的类型(例如DoubleFloat )。

In Swift's standard library they use AnySequence , AnyGenerator ,... (generic structs) in order to have an abstract type of a protocol which has Self requirements. 在Swift的标准库中,他们使用AnySequenceAnyGenerator ,...(通用结构)以具有具有Self要求的抽象类型的协议。 Unfortunately you cannot make a type AnyProtocolA<FloatingPointType> because the generic type itself has Self requirements. 不幸的是,您无法创建类型AnyProtocolA<FloatingPointType>因为通用类型本身具有Self要求。

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

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