HIT해

[Swift 기초문법 - 31] dictionary grouping 본문

Swift/Swift 기초문법

[Swift 기초문법 - 31] dictionary grouping

힛해 2024. 8. 14. 06:22
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]

 

 

 

프로젝트 적용예시

데이터가 여러개 있고 이를 분류 해야할때 유용하게 사용할 수 있다.

해당 날짜의 데이터만 가져온다거나..