Common Member Closures
filter
→ returns array elements that pass a certain condition
map
→ returns array elements transformed by a function
reduce
→ returns the sum of array elements plus an initial value
reverse
→ in-line reverses the array order
sort
→ in-line sort of values w/in the array
sorted
→ returns a copy of a sorted array of values of a known type
Counting Frequencies in an Array
let items = ["a", "b", "a", "c"]
let mappedItems = items.map { ($0, 1) }
let counts = Dictionary(mappedItems, uniquingKeysWith: +)
- use when you want to count how often each item appears
mappedItems
→ creates an array of key-value pairs using tuples, where each value is the number 1
counts
→ dictionary from that tuple array that adds the 1s together
Find the Difference Between Two Arrays
extension Array where Element: Hashable {
func difference(from other: [Element]) -> [Element] {
let thisSet = Set(self)
let otherSet = Set(other)
return Array(thisSet.symmetricDifference(otherSet))
}
}
let names1 = ["John", "Paul", "Ringo"]
let names2 = ["Ringo", "Paul", "George"]
let differenceInArrays = names1.difference(from: names2)
- sets have
symmetricDifference
function
- convert the arrays to Sets, then convert the result back