Swift 문법 - 컬렉션 타입 : 세트(Set)

eelijus·2022년 12월 26일
0

Swift Syntax

목록 보기
8/11

💡 컬렉션 타입 중 Set

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html


Set

순서가 지정되지 않고, 멤버가 유일한 것을 보장하는 컬렉션 타입. 집합연산에 많이 활용된다.

타입에 관해 축약형이 없음. 타입 추론을 사용하면 array로 타입을 지정해버린다.

배열(Array)과 세트(Set)

세트와 배열은 모두 단일 변수 내에 여러 값을 보유한다. 차이는 값을 유지하는 방법에 있다.

배열세트
순서를 유지하고 중복을 포함할 수 있다.순서가 지정되지 않고 중복을 포함할 수 없다.
  • set에 중복 항목을 삽입하려고 하면 해당 명령은 무시된다. 에러는 발생하지 않음.

  • set는 빠른 검색에 최적화 되어 있다. 요소를 순서대로 탐색할 필요가 없기 때문에 세트의 크기와 상관없이 순식간에 탐색을 완료할 수 있다.

  • array는 요소를 삽입한 순서대로 저장해야 한다. 따라서 특정 요소를 검색하지 위해 첫번째 요소부터 해당 요소까지 모든 단일 항목을 확인해야 한다.

  • "내가 찾는 항목이 존재해?" 라는 질문에는 세트가 더 유용하다. Ex) 이 사전에 sujilee가 있어?

  • 배열에서 중복값들을 삭제해 고유값들만 보관하고자 할 때, 그대로 set에 담기만 하면 된다.


생성

import Foundation

//빈 Int Set 생성
//아래 네가지 표현 모두 가능
var integerSet: Set<Int> = Set<Int>()

var integerSet: Set<Int> = Set()

var integerSet: Set<Int> = []

//선언과 초기화를 동시에 해서 타입이 지정되면 Set<Int> 같은 타입 지정을 하지 않아도 된다.
var integerSet = Set([1, 2])

integerSet.insert(1994)
integerSet.insert(12)
integerSet.insert(06)

//Array로부터 Set 생성
//아래 세가지 표현 모두 가능
let characterSet: Set<Character> =  Set<Character>(["s", "u", "j", "i"])

let characterSet: Set<Character> = Set(["s", "u", "j", "i"])

let characterSet: Set<Character> = (["s", "u", "j", "i"])

print(integerSet)
//OUTPUT : [1994, 12, 6]
print(characterSet)
//OUTPUT : ["j", "i", "u", "s"]

프로퍼티를 사용한 기본적인 사용

//intergerSet가 특정 멤버를 가지고 있는지 bool로 알려줌
print(integerSet.contains(12))
//OUTPUT : true
print(integerSet.contains(42))
//OUTPUT : false

//멤버 1994 삭제
integerSet.remove(1994)
//첫번째 멤버 삭제
integerSet.removeFirst()

print(integerSet.count)
//OUTPUT : 1
print(integerSet.isEmpty)
//OUTPUT : false
import Foundation

var cadetSet: Set = ["sujilee", "jji", "hyopark"]

if let notCadet = cadetSet.remove("eelijus") {
    print(notCadet)
    //sujilee
    print(cadetSet)
    //["jji", "hyopark"]
} else {
    print("cannot find element to remvove")
}

집합연산 사용 예시

import Foundation

//Int 타입의 Set을 Array를 사용해 선언과 동시에 초기화
let setA: Set<Int> = [1, 2, 3, 4, 5]
let setB: Set<Int> = [3, 4, 5, 6, 7]

//합집합
let union: Set<Int> = setA.union(setB)
print(union)
//OUTPUT : [1, 4, 7, 6, 2, 3, 5] - 순서 고정 X

//오름차순 정렬된 union을 담는 Array 생성
let sortedUnion: [Int] = union.sorted()
print(sortedUnion)
//OUTPUT : [1, 2, 3, 4, 5, 6, 7]

//교집합
let intersection: Set<Int> = setA.intersection(setB)
print(intersection)
//OUTPUT : [3, 5, 4] - 순서 고정 X

//차집합
let subtracting: Set<Int> = setA.subtracting(setB)
print(subtracting)
//OUTPUT : [2, 1] - 순서 고정 X

//여집합
let symmetricDifference: Set<Int> = setA.symmetricDifference(setB)
print(symmetricDifference)
//OUTPUT : [2, 1, 7, 6] - 순서 고정 X

포함 관계 연산

import Foundation

let season: Set<String> = ["봄", "여름", "가을", "겨울"]

let month: Set<String> = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ,"11", "12"]

let year: Set<String> = season.union(month)

print(year)
//OUTPUT : ["겨울", "12", "봄", "가을", "1", "6", "9", "10", "8", "4", "11", "3", "5", "2", "7", "여름"]

//season과 month가 서로 베타적인가?
print(season.isDisjoint(with: month))
//OUTPUT : true

//season이 year의 부분집합인가?
print(season.isSubset(of: year))
//OUTPUT : true

//year이 season의 전체집합인가?
print(year.isSuperset(of: season))
//OUTPUT : true

//year이 month의 전체집합인가?
print(year.isSuperset(of: month))
//OUTPUT : true




참고 :

https://yagom.github.io/swift_basic/contents/03_collection_types/

https://seons-dev.tistory.com/93

profile
sujileelea

0개의 댓글