首页 > 解决方案 > 如何获取用于构建扩展的数组的 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
        
    }
    
}

标签: swift

解决方案


文档中,我们可以看到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()
    }
}

推荐阅读