Sum an [Int] with reduce(0, +), pick a random element with randomElement() (it returns an optional), and read by index only after checking indices.contains(i). Two things trip people up: summing very large integers stops the app with an overflow trap, and summing money as Double gives 0.30000000000000004 for 0.1 + 0.2. Use Decimal for money.
SWIFT TIPS · SWIFT
First posted on September 24, 2018 for Swift 4.2, as "[Swift 4.2] Array Edition". Rewritten on November 17, 2026. All code and output below was run on a Mac with Swift 6.2.3 (Xcode 26.2) on macOS 26.0.1. The 2018 snippet was type-checked against the iOS 26.2 SDK.
The 2018 post promised two array tips: how to pick one element, and how to sum all of them. The first one only had a heading. The second showed array.reduce(0, +) inside a view controller and printed 25. That one line is still the right way to add up numbers in Swift. This rewrite fills in the missing half and adds the cases where a simple sum gives the wrong answer.
The everyday operations
let scores = [0, 1, 3, 5, 7, 9]
// Sum
print("sum:", scores.reduce(0, +))
// Pick one at random, and pick safely by index
print("random element is nil for []:", [Int]().randomElement() == nil)
print("first:", scores.first ?? -1, "last:", scores.last ?? -1)
let index = 10
print("index 10 safe:", scores.indices.contains(index) ? scores[index] : -1)
// Filter, count, min, max
print("odd:", scores.filter { $0 % 2 == 1 })
print("count over 4:", scores.count(where: { $0 > 4 }))
print("min/max:", scores.min() ?? -1, scores.max() ?? -1)
// Average needs a Double
let average = scores.isEmpty ? 0 : Double(scores.reduce(0, +)) / Double(scores.count)
print("average:", average)
// Money: sum Decimal, not Double
let prices = [0.1, 0.2]
print("Double 0.1 + 0.2 == 0.3:", prices.reduce(0, +) == 0.3, prices.reduce(0, +))
Here is what it printed:
sum: 25
random element is nil for []: true
first: 0 last: 9
index 10 safe: -1
odd: [1, 3, 5, 7, 9]
count over 4: 3
min/max: 0 9
average: 4.166666666666667
Double 0.1 + 0.2 == 0.3: false 0.30000000000000004
A few notes on those lines:
- Picking one element.
randomElement(),firstandlastall return an optional, because the array might be empty. The test confirms thatrandomElement()on an empty array isnilrather than a crash. Give each one a fallback with??, or unwrap it withif let. - Reading by index.
scores[10]on a six-element array stops the app. Checkingscores.indices.contains(index)first is the plain way to make it safe. - Counting with a condition.
count(where:)was added to the standard library in Swift 6. On older toolchains,filter { ... }.countgives the same answer. - Averages. Dividing two
Intvalues throws away the fraction, so convert toDoublefirst, and handle the empty array, where you would otherwise divide by zero.
When a sum goes wrong
Integer overflow
Swift checks integer arithmetic. I compiled a two-line program that sums [Int.max, 1] with reduce(0, +). Built in debug and with -O, it stopped both times with exit code 133, which is a trap, and printed nothing at all. In an app that's a crash with no message for the user.
Counts of items or taps won't get near Int.max. Sums of values you don't control, such as amounts from a server in the smallest currency unit, can. When that's possible, addingReportingOverflow tells you instead of crashing. The test below uses it to detect the overflow.
Money as Double
The first test printed false for 0.1 + 0.2 == 0.3 with Double, because the total was 0.30000000000000004. Binary floating point can't store 0.1 exactly. That's fine for measurements and terrible for prices, where a cent off shows up in a receipt.
Decimal 0.1 + 0.2 == 0.3: true 0.3
addingReportingOverflow: -9223372036854775808 overflow: true
Decimal made from strings gave exactly 0.3. Create it from a string, as in the test, not from a Double literal, which would carry the floating-point error over.
What the 2018 version said
The snippet put the print call directly in the class body:
class ExampleViewController: UIViewController {
let arrayInts = [ 0, 1, 3, 5, 7, 9 ]
...
func sum(array:[Int]) -> Int {
return array.reduce(0, +)
}
print(sum(array: arrayInts)) // 25
}
Swift doesn't allow statements there, only declarations. Type-checked as posted, it fails in both Swift 5 and Swift 6 mode, starting with "expected 'func' keyword in instance method declaration". Moving the print into viewDidLoad() fixes it, and the 25 it prints is correct.
A quick check for your project
- Search for
[0]and other fixed indexes on arrays that come from the network or the user. Each one is a possible crash on an empty response. - Search for prices or totals typed as
DoubleorFloat. Move them toDecimal, or to integer cents. - Look for averages that divide by
countwithout checking for an empty array.
Keep reading on JR Devhub
Comments