How can we create unique object list in Swift language like NSSet
& NSMutableSet
in Objective-C.
相关问题
- “Zero out” sensitive String data in Swift
- SwiftUI: UIImage (QRCode) does not load after call
- Get the NSRange for the visible text after scroll
- UIPanGestureRecognizer is not working in iOS 13
- What does a Firebase observer actually do?
相关文章
- Using if let syntax in switch statement
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- Is there a Github markdown language identifier for
- How can I vertically align my status bar item text
- Adding TapGestureRecognizer to UILabel in Swift
- Attempt to present UIAlertController on View Contr
- Swift - Snapshotting a view that has not been rend
Always in such a case the critical factor is how to compare objects and what types of objects go into the Set. Using a Swift Dictionary, where the Set objects are the dictionary keys, could be a problem based on the restrictions on the key type (String, Int, Double, Bool, valueless Enumerations or hashable).
If you can define a hash function on your object type then you can use a Dictionary. If the objects are orderable, then you could define a Tree. If the objects are only comparable with
==
then you'll need to iterate over the set elements to detect a preexisting object.The above is an example of building a Swift
Set
; the example used objects that are onlyEquatable
- which, while a common case, doesn't necessarily lead to an efficientSet
implementations (O(N) search complexity - the above is an example).You can use any Objective-C class in Swift:
So I think creating a Set with an array is a terrible idea - O(n) is the time complexity of that set.
I have put together a nice Set that uses a dictionary: https://github.com/evilpenguin/Swift-Stuff/blob/master/Set.swift
As of Swift 1.2 (Xcode 6.3 beta), Swift has a native set type. From the release notes:
Here are some simple usage examples:
but there are far more methods available.
Update: Sets are now also documented in the "Collection Types" chapter of the Swift documentation.
I wrote a function to solve this problem.
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 toExtensibleCollectionType
protocol if you like.I've built an extensive
Set
type similar to the built-inArray
andDictionary
- here are blog posts one and two and a GitHub repository: