Arrays
1、You can declare an array either explicitly or taking advantage of Swift's type inference. Here's an example of an explicit declaration:
let numbers: Array<Int>
Swift can also infer the type of the array from the type of initializer:
@H_403_7@
let inferredNumbers = Array<Int>()
Another,shorter,way to define an array is by enclosing the type inside square brackets,like so:
let alsoInferredNumbers = [Int]()
This isthe most common declaration formfor an array.
When you declare an array,you might want to give it initial values. You can do that usingarray literals,which is a concise way to provide array values. An array literal is a list of values separated by commas and surrounded by square brackets:
let evenNumbers = [2,4,6,8]
It's also possible to create an array with all of its values set to a default value:
let allZeros = [Int](count: 5,repeatedValue: 0)
var players = ["Alice","Bob","Cindy","Dan"] print(players.isEmpty) // > false if players.count < 2 { print("We need at least two players!") } else { print("Let's start!") } // > Let's start! var currentPlayer = players.first print(currentPlayer) // > Optional("Alice") print(players.last) // > Optional("Dan") currentPlayer = players.minElement() print(currentPlayer) // > Optional("Alice") print([2,3,1].first) // > Optional(2) print([2,1].minElement()) // > Optional(1)
As you might have guessed,arrays also have amaxElement()
method.
Now that you've figured out how to get the first player,you'll announce who that player is:
if let currentPlayer = currentPlayer { print("\(currentPlayer) will start") } // > Alice will start
3、You can use the subscript Syntax with ranges to fetch more than a single value from an array:
let upcomingPlayers = players[1...2] print(upcomingPlayers) // >["Bob","Cindy"]
As you can see,the constantupcomingPlayers
is actually an array of the same type as the original array. You can use any index here as long as the start value is smaller than the end value and they're both within the bounds of the array.
4、You can check if there's at least one occurrence of a specific element in an array by usingcontains(_:)
,which returnstrue
if it finds the element in the array,andfalse
if it doesn't.
func isPlayerEliminated(playerName: String) -> Bool { if players.contains(playerName) { return false } else { return true } }
You could even test for the existence of an element in a specific range:
players[1...3].contains("Bob") // > true
5、You can add Eli to the end of the array using
append(_:)
players.append("Eli")
You can also append elements using the+=
operator:
players += ["Gina"]
The right-hand side of this expression is an array with a single element,the string "Gina".
Here,you added a single element to the array but you see how easy it would be to appendmultiple items by adding more namesafter Gina's.
6、You want to add Frank to the list between Eli and Gina. To do that,you can useinsert(_:atIndex:)
:
players.insert("Frank",atIndex: 5)
TheatIndex
argument defines where you want to add the element. Remember that the array is zero-indexed.
7、You can remove the last one in the players list easily withremoveLast()
:
var removedPlayer = players.removeLast() print("\(removedPlayer) was removed") // > Gina was removed
This method does two things: It removes the last element andthen it returns it,in case you need to print it or store it somewhere else.
To remove Cindy from the game,you need to know the exact index where her name is stored. Looking at the list of players,you see that she's third in the list,so her index is 2.
removedPlayer = players.removeAtIndex(2) print("\(removedPlayer) was removed") // > Cindy was removed
How would youget the index of an element? There's a method for that!indexOf(_:)
returns thefirst indexof the element,because the array might contain multiple copies of the same value. If the method doesn't find the element,it returnsnil
.
8、Frank has decided that everyone should call him Franklin from now on.
print(players) // > ["Alice","Eli","Frank"] players[3] = "Franklin" print(players) // > ["Alice","Franklin"]As the game continues,some players are eliminated and new ones come to replace them. Luckily,you can also use subscripting with ranges to update multiple values in a single line of code:
players[0...1] = ["Donna","Craig","Brian","Anna"] print(players) // > ["Donna","Anna","Franklin"]
9、If you want to sort the entire array,you should usesort()
:
players = players.sort() print(players) // > ["Anna","Donna",monospace; font-size:1em; border:0px; outline:0px; vertical-align:baseline; background:transparent">sort()does exactly what you expect it to do: It returnsa sorted copyof the array.If you'd like to sort the array in place instead of returning a sorted copy,monospace; font-size:1em; border:0px; outline:0px; vertical-align:baseline; background:transparent">sortInPlace().10、If you also need the index of each element,you can iterate over the return value of the array's
enumerate()
method,which returns a tuple with the index and value of each element in the array.for (index,playerName) in players.enumerate() { print("\(index + 1). \(playerName)") } // > 1. Anna // > 2. Brian // > 3. Craig // > 4. Donna // > 5. Eli // > 6. Franklin
11、reduce(_:combine:)
take an initial value as the first argument and accumulates every value in the array in turn,using the combine operation.
let scores = [2,2,8,1,2] let sum = scores.reduce(0,combine: +) print(sum) // > 21
12、filter(_:)
returns a new array by filtering out elements from the array on which it's called.Its only argument is a closure that returns a Boolean,and it will execute this closure once for each element in the array. If the closure returns true,filter(_:)
will add the element to the returned array; otherwise it will ignore the element.
print(scores.filter({ $0 > 5 })) // > [8,6]
13、
map(_:)
also takes a single closure argument. As its name suggests,it maps each value in an array to a new value,using the closure argument.