Search
Duplicate

Dictionary(…, uniquingKeysWith: +)

생성일
2024/07/31 01:43
태그
Grammar

Dictionary(…, uniquingKeysWith: +)

스위프트에서 딕셔너리를 생성할 때 중복된 키가 발생할 경우 어떻게 처리할지 지정하는 방식이다.

Dictionary 생성자

여기서 Dictionary 생성자는 시퀀스를 입력으로 받아 딕셔너리를 생성하는 형태이다.
시퀀스의 각 요소는 (key, value) 형식의 튜플이어야 한다.

uniquingKeysWith 매개변수

uniquingKeysWith 는 중복된 키가 발생했을 때 어떻게 처리할지를 지정하는 클로저를 받는다.
이 클로저는 두 개의 값을 받아 하나의 값으로 결합한다.

+ 연산자

+ 연산자는 두 숫자를 더하는 역할
따라서 uniquingKeysWith: + 는 중복된 키가 발생할 때 값을 더하여 결합한다.

예제 코드

// // main.swift // Swift_3009 // // Created by KIM Hyung Jun on 7/31/24. // import Foundation var coords: [(Int, Int)] = [] for _ in 0..<3 { let input = readLine()!.split(separator: " ").map { Int($0)! } coords.append((input[0], input[1])) } let x = Dictionary(coords.map { ($0.0, 1) }, uniquingKeysWith: +) let y = Dictionary(coords.map { ($0.1, 1) }, uniquingKeysWith: +) // 딕셔너리를 사용해 x좌표와 y좌표가 몇 번 등장했는지 count 해주고, 1번 등장한 좌표 출력 print(x.first { $0.value == 1 }!.key, y.first { $0.value == 1 }!.key)
Swift
복사