Swift 从任意迭代器获取RawRepresentable的泛型数组

Swift 从任意迭代器获取RawRepresentable的泛型数组,swift,generics,enums,Swift,Generics,Enums,我看到了这个答案 现在我尝试创建一个方法,该方法将返回字符串数组 使用枚举的原始值 所以我做了: class func enumValues<T>(from array: AnyIterator<T>) -> [T] where T:RawRepresentable, T:Hashable { var tempArray = [T]() for item in array{ tempArray.append(item.rawValue

我看到了这个答案

现在我尝试创建一个方法,该方法将返回字符串数组 使用枚举的原始值

所以我做了:

class func enumValues<T>(from array: AnyIterator<T>) -> [T] where T:RawRepresentable, T:Hashable {
    var tempArray = [T]()
    for item in array{
        tempArray.append(item.rawValue)
    }
    return tempArray
}
类func枚举值(来自数组:AnyIterator)->[T]其中T:RawRepresentable,T:Hashable{
var tempArray=[T]()
用于数组中的项{
tempArray.append(item.rawValue)
}
返回临时数组
}
但是,我得到了这个错误:

参数类型“T.RawValue”与预期类型不符 “可散列”

参数类型“T.RawValue”与预期类型不符 “可代表性”

我如何解决这个问题?
谢谢

如果要返回包含数组元素原始值的数组, 因此,返回类型应该是
T.RawValue
(以及约束
T:Hashable
不需要):

func枚举值(来自数组:AnyIterator)->[T.RawValue],其中T:RawRepresentable{
var tempArray:[T.RawValue]=[]
用于数组中的项{
tempArray.append(item.rawValue)
}
返回临时数组
}
可以简化为

func enumValues<T>(from array: AnyIterator<T>) -> [T.RawValue] where T: RawRepresentable {
    return array.map { $0.rawValue }
}
func枚举值(来自数组:AnyIterator)->[T.RawValue],其中T:RawRepresentable{
返回array.map{$0.rawValue}
}
或更一般地,对于任何原始代表物序列:

func enumValues<S: Sequence>(from sequence: S) -> [S.Iterator.Element.RawValue]
    where S.Iterator.Element: RawRepresentable {

    return sequence.map { $0.rawValue }
}
func枚举值(来自序列:S)->[S.Iterator.Element.RawValue]
其中S.Iterator.Element:RawRepresentable{
返回sequence.map{$0.rawValue}
}
另一方面,人们可能会问,这是否值得一个单独的功能 因为您可以直接在 给定迭代器/序列/数组

func enumValues<S: Sequence>(from sequence: S) -> [S.Iterator.Element.RawValue]
    where S.Iterator.Element: RawRepresentable {

    return sequence.map { $0.rawValue }
}