Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active December 29, 2015 02:24
Show Gist options
  • Save KentarouKanno/ff1715e062d483fac3f5 to your computer and use it in GitHub Desktop.
Save KentarouKanno/ff1715e062d483fac3f5 to your computer and use it in GitHub Desktop.
for - in

for - in (forEach)

--- 番号配列 ---

let numArray = ["1","2","3","4","5"]

★ 前から取り出し

for num in numArray {
    print(num)
}

//=>
1
2
3
4
5

★ 前から取り出してブロック内で処理する

numArray.forEach{ print($0) }

//=>
1
2
3
4
5

★ 後ろから取り出し

for num in numArray.reverse() {
    print(num)
}

//=> 
5
4
3
2
1

★ Index付きで前から取り出し

// numはタプル 
for num in numArray.enumerate() {
    print(num)
}

//=> 
(0, "1")
(1, "2")
(2, "3")
(3, "4")
(4, "5")


for (index, value) in numArray.enumerate() {
    print("\(index),\(value)")
}

//=> 
0,1
1,2
2,3
3,4
4,5

★ Index付きで取得してブロック内で処理する

numArray.enumerate().forEach { print($0) }

//=> 
(0, "1")
(1, "2")
(2, "3")
(3, "4")
(4, "5")

★ Index付きで後ろから取り出し

for num in numArray.enumerate().reverse() {
    print(num)
}

//=> 
(4, "5")
(3, "4")
(2, "3")
(1, "2")
(0, "1")

numArray.enumerate().reverse().forEach { print($0) }

★ 数の大きい順に並び替えた配列を前から取り出し

for num in numArray.sort({$0 > $1}) {
    print(num)
}

//=> 
5
4
3
2
1

numArray.sort(>).forEach { print($0) }
for num in Set(numArray) {
    print(num)
}

//=> 
4
2
1
5
3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment