[swift] 35. dictionary grouping

RudinP·2023년 10월 3일
0

Study

목록 보기
53/227
  • 콜렉션 데이터 그룹으로 묶기
  • 기본적인 dictionary는 key-value 페어. 여기서 key를 기준으로 묶이는건 동일하나, value 부분에 collection이 들어간다고 생각하면 됨.
enum FriendType{
	case normal, best
}

class Friend{
	var name: String
    var type: Friendtype
}

var FriendList = [
	Friend(name: "a", type: .normal)
    Friend(name: "b", type: .normal)
    Friend(name: "c", type: .best)
    Friend(name: "d", type: .normal)
]

let groupedFriends : [FriendType : [Friend]] = Dictionary(grouping: FriendList, by: {$0.type})
//let groupedFriends = Dictionary(grouping: FriendList, by:{(friend) -> FriendType in return friend.type} )
//[normal: [{name:"a",normal}, {name:"b",normal}, {name:"d", normal}]], [best: [{name: "c", best}]] 

groupedFriends[.normal] //[{name:"a",normal}, {name:"b",normal}, {name:"d", normal}]
groupedFriends[.best] //[{name: "c", best}]
profile
곰을 좋아합니다. <a href = "https://github.com/RudinP">github</a>

0개의 댓글