diff --git a/Tutorial/Tutorial.playground/Contents.swift b/Tutorial/Tutorial.playground/Contents.swift index 9b0d9f6..b6ba2f1 100644 --- a/Tutorial/Tutorial.playground/Contents.swift +++ b/Tutorial/Tutorial.playground/Contents.swift @@ -10,6 +10,13 @@ import Foundation ... ] */ + +struct Champ: Decodable { + let key: String + let name: String +} + + let champsFilePath = Bundle.main.path(forResource: "champs", ofType: "json") /* @@ -24,9 +31,18 @@ let selectedIndexesFilePath = Bundle.main.path(forResource: "selectedIndexes", o let champsData = FileManager.default.contents(atPath: champsFilePath!) let selectedIndexesData = FileManager.default.contents(atPath: selectedIndexesFilePath!) -let champs = try JSONSerialization.jsonObject(with: champsData!, options: []) -let selectedIndexes = try JSONSerialization.jsonObject(with: selectedIndexesData!, options: []) +let decoder = JSONDecoder() +let champs = try decoder.decode([Champ].self, from: champsData!) +let selectedIndexes = try decoder.decode([Int].self, from: selectedIndexesData!) // TODO: selectedIndexes는 챔피언 목록(champs)의 key 번호 들이다. selectedIndexes에 명시된 순서대로 챔피언들의 이름(name)을 나열하라 -let names: [String] = [] + +let dictionary = champs.reduce(into: [String: String]()) { + $0[$1.key] = $1.name +} +let names = selectedIndexes.map { + String(describing: $0) +}.compactMap { + dictionary[$0] +} print(names) diff --git a/Tutorial/Tutorial2.playground/Contents.swift b/Tutorial/Tutorial2.playground/Contents.swift index 9b0d9f6..cd07a6d 100644 --- a/Tutorial/Tutorial2.playground/Contents.swift +++ b/Tutorial/Tutorial2.playground/Contents.swift @@ -1,32 +1,40 @@ import Foundation -/* - [ - { - "key": "266", - "name": "Aatrox", - ... - }, - ... - ] - */ +struct Champ: Decodable { + let key: String + let name: String +} + + let champsFilePath = Bundle.main.path(forResource: "champs", ofType: "json") -/* - [ - 1, - 33, - ... - ] - */ let selectedIndexesFilePath = Bundle.main.path(forResource: "selectedIndexes", ofType: "json") let champsData = FileManager.default.contents(atPath: champsFilePath!) let selectedIndexesData = FileManager.default.contents(atPath: selectedIndexesFilePath!) -let champs = try JSONSerialization.jsonObject(with: champsData!, options: []) -let selectedIndexes = try JSONSerialization.jsonObject(with: selectedIndexesData!, options: []) +let decoder = JSONDecoder() +let champs = try decoder.decode([Champ].self, from: champsData!) +let selectedIndexes = try decoder.decode([Int?].self, from: selectedIndexesData!) + +extension Array where Element: Equatable { + func uniqueMap() -> Self { + return self.reduce([Element]()) { + return !$0.contains($1) ? ($0 + [$1]) : $0 + } + } +} -// TODO: selectedIndexes는 챔피언 목록(champs)의 key 번호 들이다. selectedIndexes에 명시된 순서대로 챔피언들의 이름(name)을 나열하라 -let names: [String] = [] +let names: [String] = selectedIndexes + .uniqueMap() + .compactMap { $0 } + .map { + String(describing: $0) + } + .compactMap { key in + champs.first { $0.key == key }?.name + } print(names) + + +