- iOS 12 Programming for Beginners
- Craig Clayton
- 301字
- 2021-07-02 15:05:00
Retrieving a value from an array
We discussed creating arrays as well as adding items to an array. Now, let's turn to retrieving a value from an array. Since arrays are stored by their index, we can use their index to retrieve values. By way of an example, let's retrieve California:
let state = states[3]
Now, your code should look like this:

The Results Panel shows North Carolina and not California. Remember, arrays start at 0, not 1. Therefore, for us to get California, we would actually need to use the index position of 2. Let's make that update in Playgrounds as follows:
let state = states[2]
When you are done, you should see that we get "California":

There we go!
We now have this great list of states, but someone told you that Arizona is also amazing. Instead of just adding Arizona to our list, you decide that you'd actually prefer to replace South Carolina with Arizona. We could simply look at our array and see in which index South Carolina is located. This would not be helpful, however, if it were to change, or if the state for which you were searching did not exist. So, the safe way to code this is to check the array for an item, and, if that item is found, then Swift will give us its current index position. The index(of:) method is what we will use to get the index position of South Carolina:
if let index = states.index(of:"South Carolina") { print("Current index position is \(index)") }
This is how our code and output should now appear:

Now that we have the position, we can replace South Carolina with Arizona, as follows:
if let index = states.index(of:"South Carolina") { states[index] = "Arizona" }
This is how our code should now look:

- Aptana Studio Beginner's Guide
- 物聯(lián)網(wǎng)網(wǎng)絡(luò)安全及應(yīng)用
- 物聯(lián)網(wǎng)概論(第2版)
- Spring Cloud微服務(wù)架構(gòu)進(jìn)階
- React:Cross-Platform Application Development with React Native
- 光纖通信系統(tǒng)與網(wǎng)絡(luò)(修訂版)
- Working with Legacy Systems
- Bonita Open Solution 5.x Essentials
- 組網(wǎng)技術(shù)與網(wǎng)絡(luò)管理
- Web用戶查詢?nèi)罩就诰蚺c應(yīng)用
- 精通SEO:100%網(wǎng)站流量提升密碼
- 移動(dòng)互聯(lián)網(wǎng)新思維
- 商業(yè)的本質(zhì)和互聯(lián)網(wǎng)
- 物聯(lián)網(wǎng)與智慧廣電
- 想象的互動(dòng):網(wǎng)絡(luò)人際傳播中的印象形成