Last active
March 6, 2017 18:16
-
-
Save DigitalLeaves/70dd30c4d82f856942b7cffa218169f5 to your computer and use it in GitHub Desktop.
A convenient function to get all common elements from two given sequences.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func commonElementsInSequences <T, U> (_ a: T, _ b: U) -> [T.Iterator.Element] where T: Sequence, U: Sequence, T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element { | |
var returnArray:[T.Iterator.Element] = [] | |
for aItem in a { | |
for bItem in b { | |
if aItem == bItem { | |
returnArray.append(aItem) | |
} | |
} | |
} | |
return returnArray | |
} | |
var one = ["orange", "carrot", "banana"] | |
var other = ["orange", "banana", "apple"] | |
var result = commonElementsInSequences(one, other) | |
print(result) //prints ["orange", "banana"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi there Anselme! Sorry, I didn't see your comment before.
Well, it's semantically slightly different. In this case, I'm interested in getting all occurrences of all the elements in both arrays that happen to be in the other array too. The devil, in this case, is in the details. Using your approach (which I really like and it's definitely shorter and more readable), you end up getting the elements of a that are in b, but you won't get the elements of b that are contained in a too.
This is an example of a different result using both functions:
var one = ["orange", "carrot", "banana", "banana"]
var other = ["orange", "banana", "apple","orange", "banana"]
All in all, I use this a lot for my applications, but I suppose that for other use cases, your approach is better and gives you the results you are after. Thanks for your comment!