Swift 笔记(八)

我的主力博客:半亩方塘


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:

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 is the most common declaration form for an array.

When you declare an array, you might want to give it initial values. You can do that using array 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]

The following is also a valid statement:

let array: [String] = []

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)  


2、Properties and methods

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, 3, 1].minElement())
// > Optional(1)

As you might have guessed, arrays also have a maxElement() 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 constant upcomingPlayers 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 returns true if it finds the element in the array, and false 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 append multiple items by adding more names after 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)  

The atIndex 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 with removeLast():

var removedPlayer = players.removeLast()
print("\(removedPlayer) was removed")
// > Gina was removed

This method does two things: It removes the last element and then 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 you get the index of an element? There's a method for that! indexOf(_:) returns the first index of the element, because the array might contain multiple copies of the same value. If the method doesn't find the element, it returns nil.

8、Frank has decided that everyone should call him Franklin from now on.

print(players)
// > ["Alice", "Bob", "Eli", "Frank"]
players[3] = "Franklin"
print(players)
// > ["Alice", "Bob", "Eli", "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", "Craig", "Brian", "Anna", "Eli", "Franklin"]

As you can see, the size of the range doesn't have to be equal to the size of the array that holds the values you're adding.

9、If you want to sort the entire array, you should use sort():

players = players.sort()
print(players)
// > ["Anna", "Brian", "Craig", "Donna", "Eli", "Franklin"]

sort() does exactly what you expect it to do: It returns a sorted copy of the array. If you'd like to sort the array in place instead of returning a sorted copy, you should use sortInPlace().

10、If you also need the index of each element, you can iterate over the return value of the array'senumerate() 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, 6, 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.
print(scores)
// > [2, 2, 8, 6, 1, 2]
let newScores = scores.map({ $0 * 2 })
print(newScores)
// > [4, 4, 16, 12, 2, 4]

With a single line of code, you've created a new array with all the scores multiplied by 2.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值