#21: Check if an Array Contains Elements in Swift

The idiomatic way to check whether an array contains at least one element is isEmpty.

let values = [1, 2, 3]
let empty: [Int] = []

!values.isEmpty // true
empty.isEmpty   // true

This is clearer than writing array.count > 0 and it also communicates your intent directly.

The same property is available on other collections too, so the pattern works with arrays, strings, sets, dictionaries and custom collection types.


I'm also on Twitter and GitHub.

Subscribe via RSS.