代码之家  ›  专栏  ›  技术社区  ›  erdemgc

Swift上数组的GroupBy扩展用法

  •  0
  • erdemgc  · 技术社区  · 8 年前

    我有一个由字典组成的数组。

    我试过这一行,但不知道在handler中写什么。我正在努力

    全球阵列。groupBy(处理程序:{$0[Name]})

    它给出了误差;

    无法转换“String”类型的值到闭包结果类型“_”

    我的分组如下:;

    extension Sequence {
    // Using a `typealias` because it's shorter to write `E`
    // Think of it as a shortcut
    typealias E = Iterator.Element
    
    // Declaring a `K` generic that we'll use as the type of the key
    // for the resulting dictionary. The only restriction is having
    // it conforming to the `Hashable` protocol
    func groupBy<K: Hashable>(handler: (E) -> K) -> [K: [E]] {
        // Creating the resulting dictionary
        var grouped = [K: [E]]()
    
        // Iterating over our elements
        self.forEach { item in
            // Retrieving the key based on the current item
            let key = handler(item)
    
            if grouped[key] == nil {
                grouped[key] = []
            }
            grouped[key]?.append(item)
        }
    
        return grouped
    }
    

    }

    BR,

    Erdem公司

    1 回复  |  直到 8 年前
        1
  •  1
  •   Prashant Tukadiya    8 年前

    我在用这个 extension 对数组进行分组,它工作得非常好

    extension Array {
        func grouped<T>(by criteria: (Element) -> T) -> [T: [Element]] {
            var groups = [T: [Element]]()
            for element in self {
                let key = criteria(element)
                if groups.keys.contains(key) == false {
                    groups[key] = [Element]()
                }
                groups[key]?.append(element)
            }
            return groups
        }
    }
    

    我如何使用

    array.grouped { (object:MyObjectClass) -> String in
            return object.location?.name ?? "EmptyKey"
            //Here you need to return your key 
        }