안녕하세요. kai입니다~. 이번 시간에는 Array에서 Dictionary로 변환하는 것을 하려고 합니다.
이거 어디에 써 먹으냐~? 하면요. CollectionView나 TableView등과 같이 나열하는 데 사용합니다.
예를 들어 물건들이 여러개 많은데 회사별로 묶어서 화면에 보여주고 싶다. 이런 식이죠.
자 시작해볼까요~!
참조 사이트 : https://swiftsenpai.com/swift/group-array-elements-with-dictionary/
Grouping Array Elements With Dictionary in Swift - Swift Senpai
Learn how to leverage the new Dictionary.init(grouping:by:) initializer to group array elements into a dictionary with just 1 line of code.
swiftsenpai.com
Dictionary를 사용하기 위한 선언
Struct Company를 key로 사용하여 Array -> Dictionary를 만들고자 합니다.
struct Company {
let name: String
let founder: String
}
struct Device {
let category: String
let name: String
let company: Company
}
// Define Company objects
let samsung = Company(name: "Samsung", founder: "Lee Byung-chul")
let apple = Company(name: "Apple", founder: "Steve Jobs")
let google = Company(name: "Google", founder: "Larry Page")
let deviceArray = [
Device(category: "Laptop", name: "Macbook Air", company: apple),
Device(category: "Laptop", name: "Macbook Pro", company: apple),
Device(category: "Laptop", name: "Galaxy Book", company: samsung),
Device(category: "Laptop", name: "Chromebook", company: google),
Device(category: "Mobile Phone", name: "iPhone SE", company: apple),
Device(category: "Mobile Phone", name: "iPhone 11", company: apple),
Device(category: "Mobile Phone", name: "Galaxy S", company: samsung),
Device(category: "Mobile Phone", name: "Galaxy Note", company: samsung),
Device(category: "Mobile Phone", name: "Pixel", company: google)
]
Dicitonary의 key에 대한 특성을 이용하여 Struct Company를 키로 이용할 수 있습니다.
아래 내용을 보면요.
public struct Dictionary<Key, Value> where Key : Hashable
As can be seen from the above definition, any object that conforms to the Hashable protocol can be used as a dictionary key.
해석 : 위 정의에서 볼 수 있는 것처럼 Hashable protocol에 부합하는 어떤 객체든 Dictionary key로써 사용되어 질 수 있습니다.
위 내용 때문에 struct Company를 아래와 같이 조금 수정해보겠습니다.
// Conform to Hashable protocol
struct Company: Hashable {
let name: String
let founder: String
}
이제 실제로 Dictionary를 만들어 보겠습니다. 한 줄이면 끝이죠.
let groupByCategory = Dictionary(grouping: deviceArray, by: \.category)
완성되었습니다.~~
'iOS > swift' 카테고리의 다른 글
[swift] Access Control (0) | 2021.08.10 |
---|---|
[swift] view memory 화면 설명 (0) | 2021.08.09 |
[swift] 컨트롤러간 화면 전환 (0) | 2021.08.04 |
[swift] UICollectionView 사용법 (0) | 2021.08.01 |
GCD(Grand Central Patch) (0) | 2020.07.18 |