[英]Swift generic array with type constraint
I'm trying to write a swift method that returns a generic array. 我正在尝试编写一个返回通用数组的swift方法。 I've left out some of the details, but kept the important bit that isn't working for clarity... 我遗漏了一些细节,但保留了重要的一点,这不清楚......
protocol AProtocol {
func doSomething()
}
func decode<T: AProtocol>(jsonArray: Array<AnyObject>?) -> [T: AProtocol] {
//...
var resultArray = [T: AProtocol]()
resultArray.append
//...
}
When I specify that the array contains type T: AProtocol, then the append method no longer appears 当我指定数组包含类型T:AProtocol时,则不再显示append方法
[T: AProtocol] does not have a member named append [T:AProtocol]没有名为append的成员
In this line of code: 在这行代码中:
var resultArray = [T: AProtocol]()
you are creating a dictionary having key of T
type and value of AProtocol
type. 您正在创建一个具有T
类型键和AProtocol
类型值的字典。
To create an array of AProtocol
, just use: 要创建AProtocol
数组,只需使用:
var resultArray = [AProtocol]()
otherwise if you want an array of T
: 否则,如果你想要一个T
数组:
var resultArray = [T]()
Note that the constraint of T
implementing the AProtocol
protocol is set in the function declaration, so you don't have to repeat it again when using T
in the function body. 注意,实现AProtocol
协议的T
的约束是在函数声明中设置的,因此在函数体中使用T
时不必再重复它。
这[T: AProtocol]()
不是数组,而是字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.