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 >>
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 >>
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 >>
index(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 >>
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.... Continue Reading >>
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 >>
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 >>
Nate Cook wrote a simple
shuffle() extension to arrays that implements the Fisher-Yates shuffle algorithm in Swift. I use it a lot, or at least did until GameplayKit came along in iOS 9.0 – it has its own shuffle algorithm, and so is preferable.... Continue Reading >>
iOS 9.0 has a built-in way to shuffle arrays thanks to GameplayKit, and it's a simple one-liner. Here's an example of creating an array of lottery balls and picking six random ones:... Continue Reading >>
All arrays have built-in
sorted() methods that can be used to sort the array, but they are subtly different.... Continue Reading >>
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 >>
About the Swift Knowledge Base
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions, all written for Swift 4.
Learn Swift faster!
Take your Swift learning to the next level: buy the Hacking with Swift e-book and get bonus material to help you learn faster!