Created
April 24, 2017 02:29
-
-
Save DuncanMC/baf98208ac62416bee83a68df2d02dbf to your computer and use it in GitHub Desktop.
Filtering an array
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
import UIKit | |
struct AStruct { | |
let anInt: Int | |
let aString: String | |
} | |
var array: [AStruct] | |
array = [AStruct(anInt: 10, aString: "foo"), | |
AStruct(anInt: 10, aString: "bar"), | |
AStruct(anInt: 10, aString: "foobar"), | |
AStruct(anInt: 1, aString: "apple"), | |
AStruct(anInt: 1, aString: "orange"), | |
AStruct(anInt: 1, aString: "grape"), | |
AStruct(anInt: 2, aString: "Bob"), | |
AStruct(anInt: 2, aString: "Carol"), | |
AStruct(anInt: 2, aString: "Ted"), | |
AStruct(anInt: 2, aString: "Alice"), | |
AStruct(anInt: 3, aString: "talc"), | |
AStruct(anInt: 3, aString: "quartz"), | |
AStruct(anInt: 3, aString: "carborundum"), | |
] | |
var intSet = Set<Int>() | |
let filtered = array.filter{thisStruct in | |
let theInt = thisStruct.anInt | |
if intSet.contains(theInt) { | |
return false | |
} else { | |
intSet.insert(theInt) | |
return true | |
} | |
} | |
filtered.forEach{print($0)} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The above code filters the array array to get rid of entries that have the same value for
anInt
. The first entry for any given anInt value is preserved in the filtered array.The output is: