[swift] 19. Set

RudinP·2023년 9월 22일
0

Study

목록 보기
40/227
  • swift의 collection 중 하나다.

Array와 차이점

  • 순서가 없다.
    • 빌드마다 원소의 순서가 달라진다.
  • 중복이 없다.
    • 같은 원소를 추가하더라도 중복으로 추가되지 않는다.

빈 Set 만들기

// var sample: Set<Int>
var sample = Set<Int>()

초기값이 있는 Set 만들기

var sample: Set<String> = ["수지", "영희", "철수"]

Set에 원소 추가

sample.insert("진희")
sample.insert("진희")
sample.insert("a")

sample.count // 수지, 영희, 철수, 진희, a로 5다.(중복허용x)

Set에서 인덱스로 원소 삭제

  • 정의에서는 순서가 없음
  • 내부적으로는 빌드 후 HashTable Bucket에서부터의 offset
//firstIndex는 결과가 없을 수 있으므로 옵셔널임.
//따라서 Unwrap 처리가 중요함
if(let index = sample.firstIndex(of: "진희")){
	sample.remove(at: index)
}

Set에서 원소 유무 파악

//false(Bool)
sample.contains("진희")
profile
곰을 좋아합니다. <a href = "https://github.com/RudinP">github</a>

0개의 댓글