[Swift]for in文で辞書(Dictionary)のキーと値を取得

書式
for(key,val) in 辞書名{ //処理コード
}
使用例

//辞書(Dictionary)1の定義
let cftA = ["key01": 1001, "key02": 2002, "key03": 4004, "key04": 5005]
//辞書 (Dictionary)2の定義
let cftB = ["keyA": "tokyo", "keyB": "oosaka", "keyC": "yokohama", "keyD": "saitama"]

// for in 文で辞書1の要素を取得
for (key, val) in cftA {
    print("辞書1のキー:\(key),辞書1の値:\(val)")
}

print("************")
//for in 文で辞書2の要素を取得
for (key, val) in cftB {
    print("辞書2のキー:\(key), 辞書2の値:\(val)")
}

実行結果
$ swift dict.swift
辞書1のキー:key01,辞書1の値:1001
辞書1のキー:key03,辞書1の値:4004
辞書1のキー:key02,辞書1の値:2002
辞書1のキー:key04,辞書1の値:5005
************
辞書2のキー:keyA, 辞書2の値:tokyo
辞書2のキー:keyC, 辞書2の値:yokohama
辞書2のキー:keyD, 辞書2の値:saitama
辞書2のキー:keyB, 辞書2の値:oosaka

Swift

Posted by arkgame