iOS/Swift

콜렉션 타입(Collection Types) - 셋(Sets)

Brad_Heo 2023. 4. 21. 21:58

셋(Sets)

set 형태로 저장되기 위해서는 반드시 타입이 hashable이어야만 합니다. Swift에서 String, Int, Double, Bool 같은 기본 타입은 기본적으로 hashable 입니다. Swift에서 Set 타입은 Set으로 선언 합니다.

빈 Set생성

var letters = Set<Character>()
print(letters.count)
// 0

letters.insert("a")
letters = []

배열 리터럴을 이용한 Set생성

var favoriteGeneres: Set<String> = ["Rock", "Classical", "Hip hop"]

Swift의 타입추론으로 아래와 같이 선언도 가능 합니다.

var facoriteGeneres: Set = ["Rock", "Classical", "Hip hop"]

Set의 접근과 변경

print(favoriteGenres.count)
// 3

비었는지 확인

if favoriteGenres.isEmpty {
    print("no pick")
} else {
    print("\(favoriteGenres.count) pick")
}

추가

favoriteGenres.insert("Jazz")

삭제

if let removedGenre = favoriteGenres.remove("Rock") {
    print("\(removedGenre) over")
} else {
    print("no card")
}
// Rock over

값 확인

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의 순회

for-in loop을 이용해 set을 순회할 수 있다.

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

Set 명령

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

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

Set의 멤버십과 동등 비교

Set의 동등비교와 멤버 여부를 확인하기 위해 각각 ==연산자와 isSuperset(of:), isStrictSubset(of:), isStrictSuperset(of:),isDisjoint(with:)메소드를 사용합니다.

isDisjoint(with:)는 둘간의 공통값이 없는 경우에 true를 반환 합니다.

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

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