[swift] 14. 딕셔너리

RudinP·2023년 9월 14일
0

Study

목록 보기
33/227
  • collection 중 하나

빈 딕셔너리 만들기

let emptyDictionary : [String : Int] = [String : Int]()

let emptyDictionary : [String : Int] = [:]

let emptyDictionary = [String : Int]()

let emptyDictionary : [String : Int] = Dictionary<String, Int>()

초기값이 존재하는 딕셔너리 만들기

var myFriends = ["bestFriend" : "쩡대리",
				"highschool" : "영희"
                ]

키를 통해 찾을 때 존재하지 않는 경우 기본값 정하기

let youtubeFriend = myFriends["youtube", default: "친구없음"]

키, 값 추가하기

myFriends["bestFriend"] = "개발하는 정대리"

값 수정하기

//updateValue(값, forKey: 키)
myFriends.updataeValue("수잔", forKey: "girlFriend")
  • 없는 경우 추가된다.

개수 가져오기

myFriends.count

반복

for item in myFriends{
	print("item: \(item)")
}
  • 출력: item: (key: "", value: "")

nil 주의

dict["Apple"] = nil은 해당 페어를 완전히 삭제하는 것이다.
[String: String?]에서 값을 nil로 하고 싶다면 서브스크립트 문법으로 불가능하다.
이 때는 dict.updateValue(nil, forKey: "Melon") 식으로 해주어야 한다.

profile
곰을 좋아합니다. <a href = "https://github.com/RudinP">github</a>

0개의 댓글