- iOS 12 Programming for Beginners
- Craig Clayton
- 283字
- 2021-07-02 15:05:01
Removing items from an array
Now, it is time to start deleting items from our array. Let's delete the first item from our list. We have a convenience method for removing items from an array, called removeFirst(). This method will remove the first item from our array, which, in our case, is Florida. Let's remove Florida and add this line above our for...in loop:
let updatedStates = states.removeFirst()
for state in states {
print(state)
}
This is how our code and output should now look:

Since we removed Florida, all of our states' index positions will be updated to move one position closer to the top of the array. But what if we wanted to remove an item that was not first? To do this, we can use the remove(at:) convenience. So, let's remove North Carolina and New York, which are sitting at positions 2 and 4, respectively. We will add the following above our for...in loop:
states.remove(at:2) states.remove(at:4)
This is how our code and output should now look:

Now, both North Carolina and New York have been removed. You will see that California and Ohio did not move, but Colorado and Nevada moved up closer to the top of the list. To remove the remaining six items, we could use remove(at:) for each one, but instead we will use the simpler method of removeAll(). So, let's use removeAll() in Playgrounds:
states.removeAll()
Now, your code should look something like this:

Now, we are back to where we started with an empty array. We have only scratched the surface of arrays. We will do more with arrays later in this book, but we first need to look at the next collection type: dictionaries.
- Modern JavaScript Web Development Cookbook
- 異構(gòu)基因共表達(dá)網(wǎng)絡(luò)的分析方法
- 計(jì)算機(jī)網(wǎng)絡(luò)與通信(第2版)
- 大話社交網(wǎng)絡(luò)
- 區(qū)塊鏈輕松上手:原理、源碼、搭建與應(yīng)用
- Kong網(wǎng)關(guān):入門、實(shí)戰(zhàn)與進(jìn)階
- OMNeT++與網(wǎng)絡(luò)仿真
- INSTANT KineticJS Starter
- 4G小基站系統(tǒng)原理、組網(wǎng)及應(yīng)用
- 計(jì)算機(jī)網(wǎng)絡(luò)技術(shù)及應(yīng)用
- jQuery Mobile Web Development Essentials
- AWS Lambda Quick Start Guide
- 圖解物聯(lián)網(wǎng)
- 小型局域網(wǎng)組建
- Building Microservices with Spring