How to create array of unique object list in Swift

后端 未结 11 2101
猫巷女王i
猫巷女王i 2020-11-27 05:20

How can we create unique object list in Swift language like NSSet & NSMutableSet in Objective-C.

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 05:57

    I wrote a function to solve this problem.

    public func removeDuplicates(aCollection: C) -> C {
        var container = C()
    
        for element in aCollection {
            if !contains(container, element) {
                container.append(element)
            }
        }
    
        return container
    }
    

    To use it, just pass an array which contains duplicate elements to this function. And then it will return a uniqueness-guaranteed array.

    You also can pass a Dictionary, String or anything conforms to ExtensibleCollectionType protocol if you like.

提交回复
热议问题