2015年5月5日 星期二

練習基本for迴圈

有趣的是,要小心,不要寫出無限 i = i +1 之類的無限迴圈,不然風扇啟動,xcode就要重開了@@!

參考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)。你可以在遍历部分分解元祖并储存在临时变量或者常量中。
1
2
3
4
5
6
7
for (index, value) in enumerate(shoppingList) {     println("Item \(index + 1): \(value)")
}
// 元素 1: Six eggs
// 元素 2: Milk
// 元素 3: Flour
// 元素 4: Baking Powder
// 元素 5: Bananas
如需更多for-in 循环信息, 参见 For Loops.
出處:http://letsswift.com/2014/06/collection-types/
參考3:

数组的迭代访问

你可以通过for-in循环来迭代访问整个数组的值。
  1. for item in shoppingList {
  2. println(item)
  3. }
  4. // Six eggs
  5. // Milk
  6. // Flour
  7. // Baking Powder
  8. // Bananas
如果要获得每个元素的索引及其对应的值,可以使用全局的enumerate方法来迭代使用这个数组。enumerate方法对每个元素都会返回一个由索引值及对应元素值组成的元组。你可以把元组中的成员转为变量或常量来使用
  1. for (index, value) in enumerate(shoppingList) {
  2. println("Item \(index + 1): \(value)")
  3. }
  4. // Item 1: Six eggs
  5. // Item 2: Milk
  6. // Item 3: Flour
  7. // Item 4: Baking Powder
  8. // Item 5: Bananas
要获得关于for-in循环的更多资料,请查看For Loops
http://c.biancheng.net/cpp/html/2292.html


練習代碼
對應Rob Swift 29

<pre class="code prettyprint">

// Playground - noun: a place where people can play
import UIKit
for 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)")
}

沒有留言:

張貼留言

歡迎網友的交流與分享,謝謝。