Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create array of unique object list in Swift

Tags:

swift

nsset

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

like image 261
Subramanian P Avatar asked Jun 04 '14 17:06

Subramanian P


People also ask

What is NSSet in Swift?

NSSet is “toll-free bridged” with its Core Foundation counterpart, CFSet . See Toll-Free Bridging for more information on toll-free bridging. In Swift, use this class instead of a Set constant in cases where you require reference semantics.

Can array have different data types in Swift?

Swift Array – With Elements of Different TypesIn Swift, we can define an array that can store elements of any type. These are also called Heterogenous Collections. To define an array that can store elements of any type, specify the type of array variable as [Any].

What is .first in Swift?

Swift version: 5.6. The first() method exists on all sequences, and returns the first item in a sequence that passes a test you specify.


3 Answers

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.

like image 158
Martin R Avatar answered Oct 18 '22 07:10

Martin R


You can use any Objective-C class in Swift:

var set = NSMutableSet()
set.addObject(foo)
like image 44
Austin Avatar answered Oct 18 '22 07:10

Austin


Swift has no concept of sets. Using NSMutableSet in Swift might be slower than using a Dictionary that holds dummy values. You could do this :

var mySet: Dictionary<String, Boolean> = [:]
mySet["something"]= 1

Then just iterate over the keys.

like image 10
Tom van der Woerdt Avatar answered Oct 18 '22 05:10

Tom van der Woerdt