Introduction
Collection algorithms help us find, sort, and organize data quickly and easily, just like sorting your books or finding a friend's phone number fast.
array.methodName(parameters)
let numbers = [1, 2, 3, 4, 5] let filtered = numbers.filter { $0 > 3 }
let names = ["Anna", "Bob", "Charlie"] let sortedNames = names.sorted()
let containsFive = numbers.contains(5)
let fruits = ["apple", "banana", "cherry", "date"] // Find fruits that start with 'b' let bFruits = fruits.filter { $0.hasPrefix("b") } // Sort fruits alphabetically let sortedFruits = fruits.sorted() // Check if 'cherry' is in the list let hasCherry = fruits.contains("cherry") print("Fruits starting with b: \(bFruits)") print("Sorted fruits: \(sortedFruits)") print("Contains cherry? \(hasCherry)")
filter algorithm on an array numbers to get only even numbers in Swift?let names = ["Anna", "Bob", "Cathy", "David"]
let result = names.contains { $0.hasPrefix("C") }
print(result)let numbers = [3, 1, 4, 2]
let sorted = numbers.sorted(by: { a, b in a > b })
print(sorted)let scores = [10, 0, 5, 0, 8]. You want to create a dictionary where keys are the scores and values are the count of how many times each score appears, but you want to ignore zero scores. Which Swift code correctly uses collection algorithms to do this?filter { $0 != 0 }.Dictionary(grouping:by:) groups scores by value, then mapValues { $0.count } counts how many times each score appears.Pass the test and this pattern moves unknown