HIT해

[Swift 기초문법 - 55] Dictionary 반복 본문

Swift/Swift 기초문법

[Swift 기초문법 - 55] Dictionary 반복

힛해 2024. 8. 19. 22:40
728x90

Swift Dictionary 를 반복하는 방법을 알아보자.

  1. for in
  2. foreacc
  3. keys, values

 

사용예시

1. for in

let myFriends : [String: Int] = ["철수" : 19, "수잔": 23, "제임스": 30]

for (name, age) in myFriends {
    print("이름: \(name), 나이: \(age)")
}

 

 

2. forEach

myFriends.forEach { (name: String, age: Int) in
    print("이름: \(name), 나이: \(age)")
}

 

 

3. keys, values

myFriends.keys.forEach { name in
    print("이름: \(name)")
}

myFriends.values.forEach { age in
    print("나이: \(age)")
}