Swift/Swift 알고리즘
[Swift] Dictionary
힛해
2024. 10. 31. 10:14
728x90
딕셔너리 생성하기
var dict = [String:Int]()
딕셔너리 갯수 확인하기
dict.count
dict.isEmpty
딕셔너리 요소 접근하기
print(dict[key]) // Optional(value)
print(dict[key,default : 100]) // value or 100
딕셔너리 요소 추가하기
1. SubScript
dict[Key] = value
2. updateValue(value, forKey: Key)
dict.updateValue(100, forKey: Key)
// 키가 없다면 추가 후 nil 리턴
딕셔너리 요소 삭제하기
1. Subscript
dict[Key] = nil
2. removeValue(forKey:)
dict.removeValue(forKey: Key)
3. removeAll()
dict.removeAll()
Key, Value 나열
// Key
dict.keys
dict.keys.sorted()
// Value
dict.values
dict.values.sorted()
딕셔너리 요소 검색하기
let condition: ((String, Int)) -> Bool = {
$0.0.contains("h")
}
// 1. contains(where:)
dict1.contains(where: condition)
// 2. first(where:)
dict1.first(where: condition)
// 3. filter
dict1.filter(condition)
번외) 딕셔너리 속 딕셔너리
var timePositions = [Int: [String:[Int]]]()
해당 구조체에서 [Int] 에 값을 추가해보자
timePositions[time, default: [:]][positionKey, default: []].append(robotId)
처음 Int 에 접근했을떄 딕셔너리가 비어있을 수 있기에
default로 딕셔너리를 초기화 해준다.
그리고 해당 딕셔너리의 키와 value (Int 배열) 을 추가해줘야하는데.
마찬가지로 Int값을 추가할 수 있도록
String Key값에 접근시 빈배열을 초기화 해준다.
마치 2차원배열처럼 사용되는 모습이다.