SWIFT-集合タイプ

28070 ワード

ソース


The Swift Language Guide (KR)の内容を引用した.ガイドはなかなかいいですね.ぜひガイドを読んでください.
SWIFTは、Array、Set、Dictionaryの3つのタイプのコレクションをサポートします.

コレクションの変更


コレクションタイプはvarまたはletに割り当てることができます.

Array


配列のサムネイル構文


アレイタイプはArrayと名付けることもできますが、Elementと略すこともできます.

空の配列を作成


以下のInt型空配列を生成できます.
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// someInts is of type [Int] with 0 items.

someInts.append(3)
// 배열에 3을 추가 했습니다.
someInts = []
// 배열을 비웠습니다. 배열의 아이템 타입은 그대로 Int로 유지됩니다.

デフォルトでは空の配列を作成


反復メソッドとカウントメソッドを使用して、デフォルトの空の配列を作成できます.
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles : Double 타입의 [0.0, 0.0, 0.0]

別のアレイを追加するアレイの作成

  • 演算子を使用して配列を接続できます.
  • var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
    // anotherThreeDoubles : [2.5, 2.5, 2.5]
    
    var sixDoubles = threeDoubles + anotherThreeDoubles
    // sixDoubles : [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

    パターンのテキスト属性


    [value 1、value 2、value 3]シェイプを使用して配列を作成できます.
    var shoppingList: [String] = ["Eggs", "Milk"]
    type 생략 가능
    var shoppingList = ["Eggs", "Milk"]

    アレイへのアクセスと変換


    アレイ内の要素数の決定
    print("The shopping list contains \(shoppingList.count) items.")
    // The shopping list contains 2 items.
    レイアウトが空かどうかを確認
    if shoppingList.isEmpty {
        print("The shopping list is empty.")
    } else {
        print("The shopping list is not empty.")
    }
    // The shopping list is not empty.
    アレイへの要素の追加
    shoppingList.append("Four")
    // shoppingList.count = 3
    shoppingList += ["Baking Powder"]
    // shoppingList.count = 4
    shoppingList += [Chocolate Spread", "Cheese", "Butter"]
    // shoppingList.count = 7
    アレイ内の特定の場所の要素アクセス
    var firstItem = shoppingList[0]
    // firstItem : "Eggs"
    
    shoppingList[4..6] = ["Bananas", "Apples"]
    // 4, 5, 6번째 인덱스 아이템을 Banana, Apples로 변환
    // 즉, 아이템 3개가 2개로 줄었다.
    特定の場所で要素を追加、削除、またはアクセス
    shoppingList.insert("Maple Syrup", at:0)
    
    let mapleSyrup = shoppingList.remove(at: 0)
    
    firstItem = shoppingList[0]
    // firstItem : "Six eggs"
    
    let apples = shoppingList.removeLast()

    整列順序


    for in loopを用いて配列順序を行うことができる.
    for item in shoppingList {
        print(item)
    }
    // Six eggs
    // Milk
    // Flour
    // Baking Powder
    // Bananas
    配列の値とインデックスが必要な場合は、列挙()メソッドを使用します.
    for (index, value) in shoppingList.enumerated() {
        print("Item \(index + 1): \(value)")
    }
    // Item 1: Six eggs
    // Item 2: Milk
    // Item 3: Flour
    // Item 4: Baking Powder
    // Item 5: Bananas

    セット(Set)


    Set形式で格納するためには、タイプはHashable(プロトコル)でなければなりません.
    基本タイプString、Int、Double、Boolは基本的にhashableプロトコルに従います.
    SWIFTでは、Setタイプが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")
    letters = []

    タイル文字を使用したセットの作成

    var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
    
    // 타입 생략가능(타입추론)
    var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]

    Setのアクセスと変更

    print("I have \(favoriteGenres.count) favorite music genres.")
    // I have 3 favorite music genres.
    
    // 비었는지 확인(isEmpty)
    if favoriteGenres.isEmpty {
        print("As far as music goes, I'm not picky.")
    } else {
        print("I have particular music preferences.")
    }
    // I have particular preferences.
    
    // 추가(insert)
    favoriteGenres.insert("Jazz")
    
    // 삭제(remove)
    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.
    
    // 값 확인(contains)
    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メンバーシップと同等の比較


    セットのピア比較とメンバーを決定します.
    ==演算子、isSuperset(of:)、isStrictSubset(of:)、isStrictSuperset(of:)、isDiscoint(with:)
    isDisjoint(with:)は、両者の間に共通値がない場合にtrueを返します.
    let houseAnimals: Set = ["🐶", "🐱"]
    let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
    let cityAnimals: Set = ["🐦", "🐭"]
    
    houseAnimals.isSubset(of: farmAnimals)
    // true
    farmAnimals.isSuperset(of: houseAnimals)
    // true
    farmAnimals.isDisjoint(with: cityAnimals)
    // ture

    辞書


    SWIFTのDictionaryタイプは、ベースクラスを接続するNSDictionaryのブリッジタイプです.

    サムネイルDictionary


    Dictionaryは[Key:Value]として宣言できます.

    空のDictionaryの作成

    var namesOfIntegers = [Int: String]()
    namesOfIntegers[16] = "sixteen"
    namesOfIntegers = [:]
    // nil dictionary

    テキストを使用したDictionaryの作成


    辞書は[key 1:value 1、key 2:value 2、key 3:value 3]として宣言できます.
    var airports: [String: String] = = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

    Dictionaryのアクセスと変更

    print("The airports dictionary contains \(airports.count) items.")
    // The airports dictionary contains 2 items.
    // 빈 Dictionary 확인
    if airports.isEmpty {
        print("The airports dictionary is empty.")
    } else {
        print("The airports dictionary is not empty.")
    }
    // The airports dictionary is not empty.
    // 값 할당
    airports["LHR"] = "London"
    // the airports dictionary now contains 3 items