# Sets
String
,Int
,Boolean
과 같은 기본타입처럼.
Set
형태로 저장되기 위해서는 반드시 타입이 hashable
이어야 합니다.
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>
var favoriteGenres: Set<String> = ["Rock","Classical","Hip hop"]
or
var favoriteGenres: Set = ["Rock","Classical","Hip hop"]
// 타입추론으로 <String> 생략
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 genre in favoriteGenres {
print("\(genre)")
}
// Classical
// Hip hop
// Rock
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
// a,b 값 모두 포함
oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
// a,b 공통된 값만 포함
oddDigits.intersection(evenDigits).sorted()
// []
// b값을 제외한 a값
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]
// a,b 값중 공통된 값을 제외한 값
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]
동등 비교를 할때 ==
연산자와 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 공식문서