swiftnsset

How to create array of unique object list in Swift


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


Solution

  • As of Swift 1.2 (Xcode 6.3 beta), Swift has a native set type. From the release notes:

    A new Set data structure is included which provides a generic collection of unique elements, with full value semantics. It bridges with NSSet, providing functionality analogous to Array and Dictionary.

    Here are some simple usage examples:

    // Create set from array literal:
    var set = Set([1, 2, 3, 2, 1])
    
    // Add single elements:
    set.insert(4)
    set.insert(3)
    
    // Add multiple elements:
    set.unionInPlace([ 4, 5, 6 ])
    // Swift 3: set.formUnion([ 4, 5, 6 ])
    
    // Remove single element:
    set.remove(2)
    
    // Remove multiple elements:
    set.subtractInPlace([ 6, 7 ])
    // Swift 3: set.subtract([ 6, 7 ])
    
    print(set) // [5, 3, 1, 4]
    
    // Test membership:
    if set.contains(5) {
        print("yes")
    }
    

    but there are far more methods available.

    Update: Sets are now also documented in the "Collection Types" chapter of the Swift documentation.