iOS/Swift문법
[Swift 문법] 딕셔너리(Dictionary) - day8
안드뽀개기
2022. 3. 15. 10:51
반응형
딕셔너리(Dictionary)
: key와 value가 쌍으로 이루어진 자료구조, 자바의 자료구조 map과 동일한 기능을 합니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 딕셔너리 | |
// 딕셔너리는 key와 value가 쌍으로 이루어짐 | |
var myFriends = [ | |
"bestFriend" : "철수", | |
"highSchoolFriend" : "영희" | |
] | |
if let myBestFriend = myFriends["bestFriend"] { | |
print("myBestFriend : \(myBestFriend)") | |
} | |
if let highSchoolFriend = myFriends["highSchoolFriend"] { | |
print("highSchoolFriend : \(highSchoolFriend)") | |
} | |
// 딕셔너리에 해당하는 key가 없으면 defaut 값을 설정할 수 있다. | |
let youtubeFriend = myFriends["youtube", default: "친구없음"] | |
print("youtubeFriend : \(youtubeFriend)") | |
실행결과 | |
myBestFriend : 철수 | |
highSchoolFriend : 영희 | |
youtubeFriend : 친구없음 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 값을 변경할 수 있음 - 1 | |
myFriends["bestFriend"] = "개발하는 철수" | |
// 값을 변경할 수 있음 - 2 | |
myFriends.updateValue("잭슨", forKey: "bestFriend") | |
// 새로운 값을 넣을 수 있다 - 1 | |
myFriends["newFriend"] = "짱구" | |
// 새로운 값을 넣을 수 있음 - 2 | |
myFriends.updateValue("유리", forKey: "girlFreind") | |
// 빈 값인 딕셔너리 초기화 - 1 | |
let emptyDictionary1: [String : Int] = [:] | |
// 빈 값인 딕셔너리 초기화 - 2 | |
let emptyDictionary2 = [String : Int]() | |
// 빈 값인 딕셔너리 초기화 - 3 | |
let emptyDictionary3: [String : Int] = Dictionary<String,Int>() | |
// 반복문으로 딕셔너리의 value를 순회 | |
for item in myFriends { | |
print("key : \(item.key), value : \(item.value)") | |
} | |
실행결과 | |
key : bestFriend, value : 잭슨 | |
key : girlFreind, value : 유리 | |
key : newFriend, value : 짱구 | |
key : highSchoolFriend, value : 영희 |
반응형