swift - 如何获取用于构建扩展的数组的 ElementType?
问题描述
我想创建一个自定义枚举函数,因此我需要知道数组中值的类型,如何读取该信息,这是我尝试过但需要更正的内容:
extension Array {
typealias EnumeratedType<T> = [(index: Int, item: T)] // T: is the type of Elements of Array!
func customEnumerated() -> EnumeratedType<ElementType> {
var enumeratedTypeArray: EnumeratedType<ElementType> = EnumeratedType()
self.sorted().forEach { item in
enumeratedTypeArray.append((index: enumeratedTypeArray.count, item: item))
}
return enumeratedTypeArray
}
}
解决方案
从文档中,我们可以看到Array
声明为:
struct Array<Element>
所以元素类型被称为Element
。您可以像这样声明您的方法:
extension Array where Element : Comparable {
// note that this doesn't need to be generic, because the type alias is in the scope of the array
typealias EnumeratedType = [(offset: Int, element: Element)]
func customEnumerated() -> EnumeratedType {
// you can simplify the forEach call to this
.init(sorted().enumerated())
}
}
请注意,约束Element : Comparable
是必需的,因为这使得无参数重载sorted
可用。
我建议您在可能的最通用类型上声明扩展,以便您的方法可用于尽可能多的类型,并返回一个EnumeratedSequence
(与返回的相同enumerated
)。这样您就不需要自己的EnumeratedType
类型别名。
// It just so happens that the element type of a Sequence is also called "Element"
// See https://developer.apple.com/documentation/swift/sequence/2908099-element
extension Sequence where Element : Comparable {
func customEnumerated() -> EnumeratedSequence<[Element]> {
sorted().enumerated()
}
}
推荐阅读
- c# - 避免使用 ASP.NET MVC(实体框架)在地址栏上显示 url
- regex - 来自 Spring Boot 的 MongoDB 正则表达式查询
- javascript - 如何将json数据转换成流程图
- oracle - 将触发器更改为插入后
- asp.net-mvc - MVC 弹出和回发
- c# - 从 xml 文档中删除特定子项
- selenium - 选择 Frame 关键字不适用于 Firefox 但适用于 Chrome
- unity3d - Unity3d 多个布尔值的工作方式类似于按下按钮时的切换
- python - NumPy 中的布尔索引比较不适用于 NaN 值
- python - 如何在 ChatterBot 中提供选择选项作为响应