Sequence Operators
Part of the Fundamentals section of Coddy's Swift journey — lesson 75 of 86.
Swift provides useful built-in properties and methods that let you quickly gather information about arrays without writing loops. These sequence operators help you perform common calculations with minimal code.
The count property returns the number of elements in an array:
let scores = [85, 92, 78, 90]
print(scores.count) // 4For numeric arrays, Swift offers methods to find the smallest and largest values. The min() and max() methods return optionals since an empty array has no minimum or maximum:
let temperatures = [72, 68, 75, 80, 65]
if let lowest = temperatures.min() {
print(lowest) // 65
}
if let highest = temperatures.max() {
print(highest) // 80
}To calculate the total of all elements, use the reduce method. It combines all values starting from an initial value:
let prices = [10, 20, 30]
let total = prices.reduce(0, +)
print(total) // 60The 0 is the starting value, and + tells Swift to add each element to the running total. Combining these operators, you can easily calculate an average:
let grades = [85, 90, 78, 92]
let average = grades.reduce(0, +) / grades.count
print(average) // 86Challenge
EasyWrite a function analyzeScores that takes scores and returns a summary string with statistics about the array.
Use sequence operators to calculate the count, minimum, maximum, and average of the scores, then format them into a single summary string.
Logic:
- Get the total count of elements using
count - Find the minimum value using
min() - Find the maximum value using
max() - Calculate the sum using
reduce(0, +)and divide by count to get the average - Return a formatted string with all statistics
Parameters:
scores([Int]): An array of integer scores (guaranteed to have at least one element)
Returns: A formatted string containing the statistics (String). Format: "Count: X, Min: X, Max: X, Avg: X"
Example: If scores is [85, 90, 78, 92], the function should return "Count: 4, Min: 78, Max: 92, Avg: 86".
Note: The average should be calculated using integer division (no decimal places).
Cheat sheet
Swift provides built-in properties and methods for working with arrays without writing loops.
The count property returns the number of elements:
let scores = [85, 92, 78, 90]
print(scores.count) // 4The min() and max() methods find the smallest and largest values. They return optionals since empty arrays have no minimum or maximum:
let temperatures = [72, 68, 75, 80, 65]
if let lowest = temperatures.min() {
print(lowest) // 65
}
if let highest = temperatures.max() {
print(highest) // 80
}The reduce method calculates the total by combining all values starting from an initial value:
let prices = [10, 20, 30]
let total = prices.reduce(0, +)
print(total) // 60Calculate an average by combining reduce with count:
let grades = [85, 90, 78, 92]
let average = grades.reduce(0, +) / grades.count
print(average) // 86Try it yourself
func analyzeScores(scores: [Int]) -> String {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input