- 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:

- 廣電5G從入門到精通
- MERN Quick Start Guide
- 物聯網信息安全
- 計算機網絡安全實訓教程(第二版)
- 計算機網絡與數據通信
- 互聯網基礎資源技術與應用發展態勢(2021—2023)
- Building RESTful Web Services with Spring 5(Second Edition)
- SSL VPN : Understanding, evaluating and planning secure, web/based remote access
- 人人都該都懂的互聯網思維
- 網絡利他行為研究:積極心理學的視角
- 設備監控技術詳解
- LwIP應用開發實戰指南:基于STM32
- Qt5 Python GUI Programming Cookbook
- 結網@改變世界的互聯網產品經理(修訂版)
- CDN技術詳解