iOS
[Swift] 콜렉션 타입 1-2 (Collection Types) - Sets
Peppo
2021. 12. 29. 20:30
728x90
Sets
Set 형태로 저장되기 위해선 반드시 타입이 hashable 이어야 합니다.
Swift에서 String, Int, Double, Bool 같은 기본 타입은 hashable입니다.
Swift에서 Set 타입은 Set으로 선언 합니다.
빈 Set 생성
var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items..")
위처럼 타입을 지정해 놓으면 아래와 같이 사용할 수 있습니다.
letters.insert("a")
print(letters)
// ["a"]
letters = []
// Set([])
배열 리터럴을 이용한 Set 생성
var favoriteGenres: Set<String> = ["Rock", "Classic", "Lofi"]
Swift의 타입추론으로 아래와 같이 선언할 수도 있습니다.
var favoriteGenres: Set = ["Rock", "Classic", "Lofi"]
Set의 접근과 변경
// 갯수 파악
print("letters is of type Set<Character> with \(letters.count) items.")
// letters is of type Set<Character> with 0 items.
// 비었는지 확인
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.
// 삭제
if let removedGenre = favoriteGenres.remove("Rock") {
print("\(removedGenre)? I'm over it.")
} 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.
Set의 순회
Array와 같이 for-in loop를 이용해 set을 순회할 수 있습니다.
for genre in favoriteGenres {
print("\(genre)")
}
// Classic
// Jazz
// Lofi
Set의 명령
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumber: Set = [2, 3, 5, 7]
a.intersection(b)
// a,b 공통된 값만 포함
oddDigits.intersection(evenDigits).sorted()
// []
a.symmetricDifference(b)
// a,b 값중 공통된 값을 제외한 값
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]
a.union(b)
// a,b 값 모두 포함
oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a.subtracting(b)
// b값을 제외한 a값
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]
Set의 멤버십과 동등 비교
동등 비교를 할때 == 연산자와
isSubset(of:), isSuperset, isStrictSubset(of:), isStrictSuperset(of:), isDisjoint(with:) 메소드를 사용합니다.
let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]
isSubset(of:)
// houseAnimals의 값이 farmAnimals의 값에 포함이 되어있는지
houseAnimals.isSubset(of: farmAnimals)
// true
isSuperset(of:)
// farmAnimals 값들이 houseAnimals 값을 다 가지고 있는지 확인
farmAnimals.isSuperset(of: houseAnimals)
// true
isDisjoint(with:)
// farmAnimals와 cityAnimals의 공통값이 없는지 확인
farmAnimals.isDisjoint(with: cityAnimals)
// true
728x90