參考1:
http://muzining.github.io/swift-cookbook/chapter2/3.html
enumerate
将同元素类型、值非空的数组转换为字典,可使用
for in循环。//该代码由木子宁工作室蜗牛君编写
var s = ""
for (i, j) in enumerate(["A","B","C","100"]) {
// "0:A", "1:B" will be printed
s += "\(i):\(j), "
}
s //"0:A, 1:B, 2:C, 3:100,
參考2:(以下就是傳說中的中文字看得懂,卻不解其意XD)
如果需要每一个元素的整形的索引值,使用enumerate函数代替会更方便,enumerate函数对于每一个元素都会返回一个包含元素的索引和值的元组(tuple)。你可以在遍历部分分解元祖并储存在临时变量或者常量中。
如需更多for-in 循环信息, 参见 For Loops.
出處:http://letsswift.com/2014/06/collection-types/
參考3:出處:http://letsswift.com/2014/06/collection-types/
数组的迭代访问
你可以通过for-in循环来迭代访问整个数组的值。
- for item in shoppingList {
- println(item)
- }
- // Six eggs
- // Milk
- // Flour
- // Baking Powder
- // Bananas
- for (index, value) in enumerate(shoppingList) {
- println("Item \(index + 1): \(value)")
- }
- // Item 1: Six eggs
- // Item 2: Milk
- // Item 3: Flour
- // Item 4: Baking Powder
- // Item 5: Bananas
http://c.biancheng.net/cpp/html/2292.html
練習代碼
對應Rob Swift 29
<pre class="code prettyprint">// Playground - noun: a place where people can playimport UIKitfor var i = 1; i <= 10; i++ {println(i * 5)}var arr = [6, 3, 8, 1]for x in arr {println(x)}for (index, x) in enumerate(arr) {println(index)}
另一個練習
參考4:
http://stackoverflow.com/questions/24028421/swift-for-loop-for-index-element-in-array
Yes. If you need the index for each element along with its value, you can use the global
enumerate() function to iterate over the array. It returns a tuple composed of the index and the value for each item in the array. For example:for (index, element) in enumerate(list) {
println("Item \(index): \(element)")
}

沒有留言:
張貼留言
歡迎網友的交流與分享,謝謝。