[Swift] Collection Types - 2. Set

Byunghoon Lee·2021년 7월 12일
0

iOS

목록 보기
3/11

# Sets

String,Int,Boolean과 같은 기본타입처럼.
Set 형태로 저장되기 위해서는 반드시 타입이 hashable이어야 합니다.

빈 Set 생성

var letters = Set<Character>()

print("letters is of type Set<Character> with \(letters.count) items.")
// letters is of type Set<Character> with 0 items.
letters.insert("a")
print(letters) // ["a"]

letters = []
print(letters) // [] << 빈배열이지만 타입은 그대로 Set<Character>

Array 리터럴을 이용한 Set 생성

var favoriteGenres: Set<String> = ["Rock","Classical","Hip hop"]
		  or
var favoriteGenres: Set = ["Rock","Classical","Hip hop"]
// 타입추론으로 <String> 생략

갯수를 알고싶을때, count 사용

print("I have \(favoriteGenres.count) favorite music genres.")
// I have 3 favorite music genres.

빈 배열인지 파악

if favoriteGenres.isEmpty {
    print("As far as music goes, I'm not picky.")
} else {
    print("I have particular music preferences.")
}
// I have particular music preferences.

추가 (insert)

favoriteGenres.insert("Jazz")
print(favoriteGenres) // ["Hip hop", "Classical", "Rock", "Jazz"]

삭제

if let removedGenre = favoriteGenres.remove("Rock") {
    print("\(removedGenre)? I'm over it.") // 지워진 아이템(원소)이 있으면 true
} else {
    print("I never much cared for that.")
}
// "Rock? I'm over it."

값이 있는지 확인

if favoriteGenres.contains("Funk") {
    print("I get up on the good foot.")
} else {
    print("It's too funky in here.")
}
// It's too funky in here.

반복 (for-in)

for genre in favoriteGenres {
  print("\(genre)")
}
// Classical
// Hip hop
// Rock

Set 명령

let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]

a.union(b)

// a,b 값 모두 포함

oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

a.intersection(b)

// a,b 공통된 값만 포함

oddDigits.intersection(evenDigits).sorted()
// []

a.subtracting(b)

// b값을 제외한 a값

oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]

a.symmetricDifference(b)

// a,b 값중 공통된 값을 제외한 값

oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]

Set의 멤버십과 동등비교

동등 비교를 할때 == 연산자와 isSubset(of:),isSuperset,isStrictSubset(of:),isStrictSuperset(of:),isDisjoint(with:) 메소드를 사용합니다.

let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]


houseAnimals.isSubset(of: farmAnimals)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.isDisjoint(with: cityAnimals)
// true

참고 : Swift 공식문서

profile
Never never never give up!

0개의 댓글