Swift Collection Set
* 스스로 공부 및 정리를 위해 The Swift Language Guide을 기반으로 요약 및 정리 한 내용입니다.
Set
- Set형태로 저장되기 위해서는 반드시 타입이 hashable이어야만합니다.
- Swift의 기본적인 타입들은 hashable입니다.
Hashable이란?
- Hashable은 hash value를 구할수 있는 것입니다(hash value는 데이터를 hash function을 사용하면 64bit의 int값으로 변환된 값).
- 이때, Hashable 이란 Hashable Protocol을 준수한다는 의미 입니다.
- Hahable이란 HashTable에서 사용 가능하다는 의미입니다.
- 예로 “ABC” 사용하면 “ABC”키값으로 거기에맞는 hash value를 가진다는 의미입니다.
- Hashable은 HashTable에서 HashKey값과 HashValue값을 가지고있습니다.
- 즉, 같은 HashValue값이라도 Key와 hashfunction에따라 계산된 결과이므로 다를수도있다는것입니다.
Set 생성
- 상수or변수 SetName = Set<데이터타입>()으로 생성 할 수 있습니다.데이터타입>
var BirdName = Set<String>()
print(type(of: BirdName))
배열리터럴을 이용한 Set생성
- 앞에 쓴 Array처럼 배열 리터럴을 통해 생성도 가능합니다
- 타입 추론도 됩니다.
let BirdsName: Set<String> = ["First", "Dragond", "Super"]
print(BirdsName)
var birdsName: Set = ["Ki","Merry","Happy"]
print(birdsName)
Set의 접근과 변경
- Array와 동일하게 .count로 갯수를 확인, .isEmpty로 원소가 비웠는지 확인가능합니다
print(birdsName.count)
if birdsName.isEmpty{
print("nil")
}
else{
print(birdsName.count)
}
- .insert를 통해 원소를 추가할수 있습니다
- Array와 달리 index로 추가하지는 못합니다.(Collection의 사진을 참조해주세요)
birdsName.insert("New")
print(birdsName)
- .remove를 통해 원소를 삭제 할수 있습니다.
- 이역시 Index를 이용하지는 못합니다.
birdsName.remove("New")
print(birdsName)
- 특정값이 존재하는지 확인 할떄는 .contains()를 이용합니다
if birdsName.contains("Ki"){
print("Yes")
}
else{
print("No")
}
- for-in loop를 통해 set을 순회할수 있습니다.
for birds in birdsName {
print(birds)
}
Set 명령
- A.union(B)의 경우, A와 B의 합집합을 의미합니다.
- A.intersection(B)의 경우, A와 B의 교집합을 의미합니다.
- A.subtracting(B)의 경우, A와 B의 A기준의 차집합을 의미합니다.
- A.symmetricDifference(B)의 경우, A와 B의 대칭차집합을 의미합니다.
let first: Set = [1,2,3,4,5]
let second: Set = [0,2,4,6,8]
let third: Set = [1,2]
let four: Set = [1,2]
let five: Set = [0,5]
print(first.union(second))
print(first.intersection(second))
print(first.subtracting(second))
print(first.symmetricDifference(second))
Set의 멤버십과 동등 비교
- Set의 동등비교와 멤버 여부를 확인하기 위해 각각 == 연산자와 isSubseb,isSuperset(of:), isStrictSubset(of:), isStrictSuperset(of:), isDisjoint(with:) 메소드를 사용합니다.
- isSubset()은 말 그대로 하위 Set인지 확인하는 것입니다. 2개가 동일한 집합이라도 true가 나옵니다(3번째예시)
- isSuperSet()은 isSubset과 반대로 상위 Set이면, true를 반환합니다. 2개가 동일한 집합이라도 true가 나옵니다(4번째예시)
- isStrictSubset()는 isSubset과 마찬가지지만, 2개가 부모관계가아닌 같은 집합인경우 isSubset에서 true가 나오지만 여기선 false가됩니다. 말그래로 좀더 엄격하게 부모,자식 Set을 나눕니다.
- isStrictSubset()는 isSuperset과 비슷하지만, 위의 isStrickSubset()과 동일하게 좀더 엄격한 규칙으로 부모,자식 Set을 구분합니다.
- isDisjoint()는 서로 겹치는 요소가 없을떄 true값을 가집니다.
print(third == four)
print(third.isSubset(of: first))
print(first.isSuperset(of: third))
print(four.isSubset(of: third))
print(four.isSuperset(of: third))
print(four.isDisjoint(with: second))
print(four.isDisjoint(with: five))