How do you create multi-dimensional arrays?
Creating an array that holds strings is as simple as writing [String]
, but what about creating an array where each item is an array of strings – an array of arrays? This is called a multi-dimensional array, because if you were to draw its contents on paper it would look like a grid rather than a line.... Continue Reading >>
How to count objects in a set using NSCountedSet
One of my favorite little gems in Cocoa Touch is called NSCountedSet
, and it's the most efficient way to count objects in a set. Here's the code:... Continue Reading >>
How to enumerate items in an array
There several ways to loop through an array in Swift, but using the enumerated()
method is one of my favorites because it iterates over each of the items while also telling you the items's position in the array.... Continue Reading >>
How to find an item in an array using firstIndex(of:)
The firstIndex(of:)
method tells you the index of an element in an array if it exists, or returns nil otherwise. Because it's an optional value, you need to unwrap it carefully or at least check the result, like this:... Continue Reading >>
How to join an array of strings into a single string
If you have an array of strings and want to merge all the elements together into a single string, it's just one line of code in Swift thanks to the joined()
method.... Continue Reading >>
How to loop through an array in reverse
If you want to read through an array in reverse, you should use the reversed()
method. You can use this as part of the regular fast enumeration technique if you want, which would give you code like this:... Continue Reading >>
How to loop through items in an array
Swift offers a selection of ways to loop through an array, but the easiest and fastest is known as fast enumeration and looks like this:... Continue Reading >>
How to randomize the order of an array: shuffle() and shuffled()
Swift has built-in methods for shuffling arrays: shuffle()
and shuffled()
, depending on whether you want the shuffling to happen in place or not.... Continue Reading >>
How to shuffle an array using arc4random_uniform()
Modern Swift code will use Swift’s own shuffle()
and shuffled()
methods, but sometimes you might find code that does it by hand using arc4random_uniform()
or similar.... Continue Reading >>
How to sort an array using sort()
All arrays have built-in sort()
and sorted()
methods that can be used to sort the array, but they are subtly different.... Continue Reading >>
How to tell if an array contains an object
It's easy to find out whether an array contains a specific value, because Swift has a contains()
method that returns true or false depending on whether that item is found. For example:... Continue Reading >>
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions, all written for Swift.
Link copied to your pasteboard.