Array Methods
Part of the Fundamentals section of Coddy's Swift journey — lesson 65 of 86.
Beyond adding and removing elements, Swift arrays come with several helpful methods that make working with collections easier.
The isEmpty property checks whether an array has any elements:
var tasks = [String]()
print(tasks.isEmpty) // true
tasks.append("Buy groceries")
print(tasks.isEmpty) // falseTo remove all elements at once, use removeAll():
var numbers = [1, 2, 3, 4, 5]
numbers.removeAll()
print(numbers) // []The reversed() method returns the elements in reverse order:
let letters = ["A", "B", "C"]
print(Array(letters.reversed())) // ["C", "B", "A"]For sorting, use sorted() to get a new sorted array, or sort() to sort the array in place:
let scores = [85, 42, 97, 63]
print(scores.sorted()) // [42, 63, 85, 97]
var prices = [9.99, 2.50, 5.75]
prices.sort()
print(prices) // [2.5, 5.75, 9.99]Notice that sorted() returns a new array while leaving the original unchanged, whereas sort() modifies the original array directly.
Challenge
EasyWrite a function processScores that takes scores and returns a formatted string with information about the scores.
The function should analyze the array and build a result string with three pieces of information.
Logic:
- Check if the array is empty using
isEmpty - If empty, return
"No scores" - Otherwise, get the sorted scores (ascending order) and the reversed scores
- Return a string combining both results
Parameters:
scores([Int]): An array of integer scores
Returns: A string in the format: "Sorted: [sorted_array], Reversed: [reversed_array]" or "No scores" if the array is empty (String)
Example: If scores is [85, 42, 97, 63], the function should return:
"Sorted: [42, 63, 85, 97], Reversed: [63, 97, 42, 85]"Note: The reversed array should be the reverse of the original array, not the sorted one.
Cheat sheet
Swift arrays provide several useful methods for working with collections:
The isEmpty property checks if an array contains any elements:
var tasks = [String]()
print(tasks.isEmpty) // true
tasks.append("Buy groceries")
print(tasks.isEmpty) // falseUse removeAll() to remove all elements from an array:
var numbers = [1, 2, 3, 4, 5]
numbers.removeAll()
print(numbers) // []The reversed() method returns elements in reverse order:
let letters = ["A", "B", "C"]
print(Array(letters.reversed())) // ["C", "B", "A"]For sorting, use sorted() to create a new sorted array, or sort() to sort in place:
let scores = [85, 42, 97, 63]
print(scores.sorted()) // [42, 63, 85, 97]
var prices = [9.99, 2.50, 5.75]
prices.sort()
print(prices) // [2.5, 5.75, 9.99]sorted() returns a new array without modifying the original, while sort() modifies the array directly.
Try it yourself
func processScores(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 Input12Arrays Basics
Declaring An ArrayAccessing ElementsModifying ArraysArray MethodsRecap - Product ListRecap - Reversed ArrayTuples