기존 delegate를 사용하던 구조에서 DataManager를 생성하여 뷰컨트롤러들에서 접근해 사용하는 방식으로 변경하였다.
그 과정에서 기존 사용하던 저장 프로퍼티의 타입을 변경해야했는데, 구현해둔 로직이 깨져 난감하던 차에 Identified collection이라는 라이브러리를 소개받았다.
-> 순서가 있는 딕셔너리라 생각하면 편하다.
struct PurchaseItem: Identifiable {
var id: Int{
item.id
}
let item: Item
var count: Int
var totalPrice: Int {
return item.price * count
}
}
var inventoryList: IdentifiedArrayOf<PurchaseItem> = []
func addItemToInventory(item: Item) {
if var item = DataManager.shared.inventoryList[id: item.id] {
item.count += 1
DataManager.shared.inventoryList[id: item.id] = item
} else {
DataManager.shared.inventoryList.append(PurchaseItem(item: item, count: 1))
}
}
inventoryList는 IdentifiedArrayOf<PurchaseItem> 타입을 갖는다.
addItemToinventory 함수 내부에서 invetoryList[id: item.id]를 append 시킨다.
이제 inventoryList 저장 프로퍼티는 PurchaseItem 타입을 순서대로 배열로 저장하고, 저장된 PurchaseItem의 id를 통해 배열 인덱스와 관계없이 inventoryList에 저장된 PurhcaseItem에 접근할 수 있다.
기존에 [Int: PurchaseItem] 타입의 딕셔너리를 inventoryList로 쓰고 있었으므로 IdentifiedArrayOf 타입을 사용함으로써 큰 코드 변경 없이 수정할 수 있었다.