Python-Loops!
ループです。
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
という辞書がある場合。'gallahad': 'the pure'のkeyとvalueを取得したい!というときは、"items()"を使います。
for k, v in knights.items():
print(k,v)
とすると、
gallahad the pure
robin the brave
と出力されます。
Swiftだと、
var knights = ["gallahad": "the pure", "robin": "the brave"]
for (k,v) in knights{
print(k,v)
で同じことができます。
Pythonに戻りまして、データと、インデックスを取得したい時には"enumerate()"を使います。
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
0 tic
1 tac
2 toe
こんな感じで出力されます。
これもSwiftでやるとなると、
for (i, v) in ["tic", "tac", "toe"].enumerated(){
print(i,v)
}
で同じことができます。少し手法は違いますが同じことができます。
次は2つまたはそれ以上のリストをループしたい時は、zip()を使います。
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print('What is your {0}? It is {1}.'.format(q, a))
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
と出力されます。
これもSwiftでやってみると、
var questions = ["name", "quest", "favorite color"]
var answers = ["lancelot", "the holy grail", "blue"]
for (q, a) in zip(questions, answers){
print("What is your \(q)? It is \(a)")
}
こんな感じになります。
この記事が気に入ったらサポートをしてみませんか?