📢기억하려고 기록해놓는 글
사전지식
세트(Set)이란?
- 같은 타입의 데이터
- 순서 없음
- 컬렉션 타입
- 세트 내의 값은 모두 유일한 값
- 세트의 요소는 해시 가능한 값
- 축약형 표현이 없고 Set<타입>() 과 같이 Set임을 명시해야함
- 추가 및 삭제 : insert(:), remove(:) -> Set를 반환
- 교집합 set.intersection(컬렉션) / 여집합 set.symmetricDifference(컬렉션) / 합집합 set.union(컬렉션) / 차집합 set.subtracting(컬렉션) 📢(여기서 컬렉션은 배열, 세트, 딕셔너리)
Array(배열)과 차이점은?
가장 큰 차이점은 배열은 세트와 달리 인덱스가 존재합니다. 그리고 중복값을 허용합니다.
Set으로 Array(배열)에서 중복값 제거하기
중복값이 있으면 안되는 데이터를 정의할때 다음과 같은 방법을 사용하면 쉽게 중복을 제거할 수 있습니다.
1234567891011121314151617181920 // Set 없이 반복문으로 중복값 제거하기 func removeDuplication(in cardsToCheck: [Int]) -> [Int]{ var duplicationRemovedCards = cardsToCheck for cardIndex in 0 ... duplicationRemovedCards.count-1 { if cardIndex + 1 <= duplicationRemovedCards.count-1 { if duplicationRemovedCards[cardIndex] == duplicationRemovedCards[cardIndex+1] { duplicationRemovedCards.remove(at: cardIndex) } } } } // Set 으로 중복값 제거하기func removeDuplication(in array: [Int]) -> [Int]{ let set = Set(array) let duplicationRemovedArray = Array(set) return duplicationRemovedArray} cs
중복값을 담고있는 array 배열을 Set
으로 변환해주면 중복된 값들을 제거한 Set
을 반환합니다. 중복값이 제거된 set를 다시 Array
array로 변환하면 중복값이 제거된 배열이 됩니다.
궁금한 점, 틀린 내용, 오타 지적, 오역 지적 등 피드백 환영합니다! 댓글로 남겨주세요!