HIT해
[Swift 기초문법 - 31] dictionary grouping 본문
728x90
dictionary grouping이란?
dictionary값들을 키 또는 값 타입에 따라 쉽게 분류해주는 함수다.
사용예시
import UIKit
enum FriendType {
case normal, best
}
struct Friend {
var name : String
var type : FriendType
}
var friendList = [
Friend(name: "철수", type: .normal),
Friend(name: "영희", type: .best),
Friend(name: "제임스", type: .best),
Friend(name: "수잔", type: .normal)
]
// grouping : 나누려는 콜렉션을 넣어준다. by : 타입에 따라서 분류해라
// 축약형
//let groupedFriends = Dictionary(grouping: friendList, by: { $0.type })
// 들어온 친구의 타입에 따라서 분류를 하겠다.
let groupedFriends = Dictionary(grouping: friendList, by: { (friend) -> FriendType in
return friend.type
})
print(groupedFriends)
groupedFriends[.normal]
groupedFriends[.best]
프로젝트 적용예시
데이터가 여러개 있고 이를 분류 해야할때 유용하게 사용할 수 있다.
해당 날짜의 데이터만 가져온다거나..
'Swift > Swift 기초문법' 카테고리의 다른 글
[Swift 기초문법 - 33] Getter, Setter (0) | 2024.08.14 |
---|---|
[Swift 기초문법 - 32] 의존성 주입 Dependency Injection (0) | 2024.08.14 |
[Swift 기초문법 - 30] class func vs static func (0) | 2024.08.14 |
[Swift 기초문법 - 29] compactMap, flatMap (0) | 2024.08.14 |
[Swift 기초문법 - 28] map (0) | 2024.08.14 |