Array - free Swift example code
About 3 min
Array - free Swift example code 관련
Array - free Swift example code
Learn Swift coding for iOS with these free tutorials – learn Swift, iOS, and Xcode
Found 11 articles in the Swift Knowledge Base for this category.
How do you create multi-dimensional arrays?
ating 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....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:...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....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:...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....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:...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:...
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....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....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....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:...