Are there any standard library calls I can use to either perform set operations on two arrays, or implement such logic myself (ideally as functionally and also efficiently as possible)?
相关问题
- “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
- Is there something like the threading macro from C
- 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
The most efficient method I know is by using godel numbers. Google for godel encoding.
The idea is so. Suppose you have N possible numbers and need to make sets of them. For example, N=100,000 and want to make sets like {1,2,3}, {5, 88, 19000} etc.
The idea is to keep the list of N prime numbers in memory and for a given set {a, b, c, ...} you encode it as
So you encode a set as a BigNumber. The operations with BigNumbers, despite the fact that they are slower than operations with Integers are still very fast.
To unite 2 sets A, B, you take
lowest-common-multiple of A and B as A and B are sets and both numbers.
To make the intersection you take
greatest common divisor.
and so on.
This encoding is called godelization, you can google for more, all the language of arithmetics written using the logic of Frege can be encoded using numbers in this way.
To get the operation is-member? it is very simple --
To get the cardinal it's a little more complicated --
you decompose the number S representing the set in product of prime factors and add their exponents. In case the set does not allow duplicates you will have all exponents 1.
Yes, Swift has the
Set
class.Swift 3.0+ can do operations on sets as:
Swift 2.0 can calculate on array arguments:
Swift 1.2+ can calculate on sets:
If you're using custom structs, you need to implement Hashable.
Thanks to Michael Stern in the comments for the Swift 2.0 update.
Thanks to Amjad Husseini in the comments for the Hashable info.
There aren't any standard library calls, but you may want to look at the ExSwift library. It includes a bunch of new functions on Arrays including difference, intersection and union.
You may want to follow same pattern as in Objective-C, which also lacks such operations, but there is a simple workaround:
how to intersect two arrays in objective C?