[Swift] Collection Types - 2. Set


# SetsStringIntBooleanなどの基本タイプのようです.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>

Array Literalを使用した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.

追加

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:)isSupersetisStrictSubset(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公式文書