Swift

<Value Type> Set

Daesiker 2024. 3. 3. 17:41
반응형
반응형

https://developer.apple.com/documentation/swift/set/

 

Set | Apple Developer Documentation

An unordered collection of unique elements.

developer.apple.com

Set이란?

Set이란 자료구조 중 하나로 배열, 딕셔너리와 같이 Value Type의 구조체이다.

Set의 특징은 다음과 같다.

  • 순서가 없는 구조체
let set:Set<Int> = [1,2,3,4,5]

print(set) // [1, 3, 2, 4, 5]
print(set) // [2, 4, 1, 3, 5]
  • Hashable 프로토콜을 준수하는 타입만 사용이 가능하다.
    • 배열에 비해 검색속도가 빠르다.
    • 해시 값을 통해 저장한다.

  • 중복 요소를 포함하지 않는다.
    • hashValue가 같으면 같은 값으로 취급하기 때문에 같은 값을 여러개 집어넣어도 1개만 저장된다.
    let set:Set<Int> = [1,2,3,4,5,2]
    
    print(set) // [1, 3, 2, 4, 5]
  • Hashable 프로토콜을 준수하므로 Hashable의 모 프로토콜인 Equatable도 준수하므로 비교연산자를 사용가능하다.
let set1:Set<Int> = [1,2,3,4,5]
let set2:Set<Int> = [2,3,4,1,5]
let set3:Set<Int> = [3,4,5,6,7]
//set은 순서를 고려하지 않고, 요소만 같으면 같은 set이다.
print(set1 == set2) // true
print(set1 == set3) // false

Set Property

  • var isEmpty : Bool
    let set1:Set<Int> = [1, 3, 5]
    let set2:Set<Int> = []
    
    print(set1.isEmpty) //false
    print(set2.isEmpty) //true
    
  • Set이 비어있는지 여부를 나타내는 Bool 값
  • var count : Int
    let set1:Set<Int> = [1,2,3,4,5]
    print(set1.count) // 5
    
  • Set안에 있는 요소의 개수를 알려주는 Int값

 

Set Method

func contains(Element) → Bool

  • Set안에 element가 포함되어있는지 여부를 Bool값으로 리턴
let set1:Set<Int> = [1,2,3,4,5]
print(set1.contains(1)) // true
print(set1.contains(6)) // false

func insert(_:Element) → (inserted: Bool, memberAfterInsert: Element)

  • Element라는 값을 추가하는데 기존에 존재하는 Element라면 inserted가 false로 리턴하고, 없는 값이면 true를 리턴한다.
  • memberAfterInsert는 언제나 추가하는 element를 가져온다.
let set1:Set<Int> = [1,2,3,4,5]
print(set1.insert(1)) // (false, 1)
print(set1) //[1, 3, 2, 4, 5]
print(set1.insert(6)) // (true, 6)
print(set1) //[1, 2, 4, 6, 3, 5]

func update(with: Element) → Element?

  • Element가 set안에 이미 존재하면 Element를 리턴
  • Element가 없으면 값을 추가 하고 nil 리턴
let set1:Set<Int> = [1,2,3,4,5]
print(set1.update(with: 1)) // Optional(1)
print(set1.insert(6)) // nil
print(set1) //[1, 2, 4, 6, 3, 5]

func union<S>(S) → Set<Element>

  • S와의 합집합을 리턴
let set1:Set<Int> = [1,2,3]
let set2:Set<Int> = [3,4,5]

let set3 = set1.union(set2)
print(set3) // [1, 2, 3, 4, 5]

func intersection<S>(S) → Set<Element>

  • S와의 교집합을 리턴
let set1:Set<Int> = [1,2,3]
let set2:Set<Int> = [3,4,5]

let set3 = set1.intersection(set2)
print(set3) // [3]

func sysmetricDifference<S>(S) → Set<Element>

  • S와의 여집합을 리턴
let set1:Set<Int> = [1,2,3]
let set2:Set<Int> = [3,4,5]

let set3 = set1.intersection(set2)
print(set3) // [1, 2, 4, 5]

func subtracting<S>(S) → Set<Element>

  • S와의 차집합을 리턴
let set1:Set<Int> = [1,2,3]
let set2:Set<Int> = [3,4,5]

let set3 = set1.subtracting(set2)
print(set3) // [1, 2]

 

반응형

'Swift' 카테고리의 다른 글

14. UI Test  (0) 2022.12.31
13. Unit Test(3)  (0) 2022.12.23
12. Unit Test(2)  (0) 2022.12.16
11. Unit Test(1)  (0) 2022.12.09
10. 멀티 스레딩과 GCD  (0) 2022.12.04