测试协议与相关类型的一致性 [英] testing protocol conformance with associated types

查看:81
本文介绍了测试协议与相关类型的一致性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用关联类型的协议,例如:

 协议可以使用{
typealias T
func populateWith(object:T)
}

以及实现协议的类:

  class DateRowType:Populatable {
func populateWith(object:NSDate){
print(object。描述)
}
}

class StringRowType:可扩展的{
func populateWith(object:String){$ b $ print(object)
}
}

但是当我尝试转换或测试一致性时,像这样: p>

  let drt = DateRowType()
let srt = StringRowType()

let rowTypes = [ (rowTypes){
p.populateWith(drt,srt)
let data = [NSDate(),foo]

for(i,p:Populatable) data [i])
}

我得到这个错误:


协议'P opulatable'只能用作通用约束,因为它具有Self或相关类型要求


什么是正确的方法来测试对象符合可扩展协议?



注意:所有需要试用的代码都包含在问题中,只需将代码块复制到操场即可。

解决方案

我不认为你能够通用整个方法,除非可能通过使用AnyObject并测试参数的类每个populateWith函数。

但是,这将工作:

  for我,p)枚举(rowTypes){
如果让dateRow = p as? DateRowType {
dateRow.populateWith(data [i] as!NSDate)
}
否则如果让stringRow = p as? StringRowType {
stringRow.populateWith(data [i] as!String)
}
}

您只需要为您添加的每个可扩展课程展开此操作。


I have a protocol that uses an associated type, as such:

protocol Populatable {
    typealias T
    func populateWith(object: T)
}

and classes that implement the protocol:

class DateRowType: Populatable {
    func populateWith(object: NSDate) {
        print(object.description)
    }
}

class StringRowType : Populatable {
    func populateWith(object: String) {
        print(object)
    }
}

but when I try to cast or test for conformance, like this:

let drt = DateRowType()
let srt = StringRowType()

let rowTypes = [drt, srt]
let data = [NSDate(), "foo"]

for (i, p: Populatable) in enumerate(rowTypes) {
    p.populateWith(data[i])
}

I get the error:

Protocol 'Populatable' can only be used as a generic constraint because it has Self or associated type requirements

What's the correct way to test if the object conforms to the Populatable protocol?

Note: all the code required to try this out is contained in the question, just copy the code blocks into a playground.

解决方案

I don't think you will be able to go generic the whole way, unless possibly by using AnyObject and testing the class of the parameter in each populateWith function.

But this will work:

for (i, p) in enumerate(rowTypes) {
    if let dateRow = p as? DateRowType {
        dateRow.populateWith(data[i] as! NSDate)
    }
    else if let stringRow = p as? StringRowType {
        stringRow.populateWith(data[i] as! String)
    }
}

You will just need to expand this for every Populatable class you add.

这篇关于测试协议与相关类型的一致性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆