How can we create unique object list in Swift language like NSSet
& NSMutableSet
in Objective-C.
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.
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].
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.
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 withNSSet
, providing functionality analogous toArray
andDictionary
.
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.
You can use any Objective-C class in Swift:
var set = NSMutableSet()
set.addObject(foo)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With