美文网首页
在闭包中使用集合:使集合有序

在闭包中使用集合:使集合有序

作者: 大爷的二舅 | 来源:发表于2018-08-05 16:53 被阅读7次

    我们都知道集合可以删选数据的重复性,唯一性,但是确定是无需的。有时候我们需要在对数据进行筛选的时候保持唯一性,这个时候集合就显得特别重要了。使用集合进行解决

    extension Sequence where Element: Hashable {
        func unique() -> [Element] {
            var seen: Set<Element> = []
            return filter{element in
                if seen.contains(element){
                    return false
                } else {
                    seen.insert(element)
                    return true
                }
            }
        }
    }
    
    let arr = [1,2,3,22,3,4,6,5,6,2].unique()
    print(arr)
    

    这样就很好的解决了数据重复性和无序性的问题。

    相关文章

      网友评论

          本文标题:在闭包中使用集合:使集合有序

          本文链接:https://www.haomeiwen.com/subject/itibvftx.html