[Swift] 4. Collection Type


swiftは、配列、辞書、および集合の3つのベースの集合タイプを提供します.

Mutability of Collections


上記のCollection typeは変更できます.
  • adding
  • removing
  • changing
  • letとして指定した場合は変更できません.サイズや内容は変えられません.

    Arrays


    同じタイプの値をシーケンスリストに保存します.
    同じ値は異なる場所で複数回保存できます.

    Array Shorthand Syntax


    Arrayで表し、Elementに値のtypeを使用します.
    簡単にElementと表すこともできます.

    Creating an Empty Array

    var someInts = [Int]()
    print("someints is of type [Int] with \(someInts.count) items.")
    // prints "someInts is of type [Int] with 0 items"
    
    someInts.append(3)
    // someInts now contains 1 value of type Int
    someInts = []
    // someInts is now an empty array, but is still of type [Int]
    

    Creating an Array with a Default Value


    Arrayの作成時にデフォルト値を設定できます.
    var threeDoubles = Array(repeating: 0.0, count: 3)
    // threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
    

    Creating an Array by Adding Two Arrays Together

    var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
    // anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5]
    
    var sixDoubles = threeDoubles + anotherThreeDoubles
    // sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

    Creating an Array with an Array Literal


    array literalを使用してarrayを作成できます.より多くの書き込み方法
    var shoppingList: [String] = ["Eggs", "Milk"]
    // shoppingList has been initialized with two initial items
    配列を宣言する場合、typeを宣言する必要はなく、自動的にtypeを指定します.
    var shoppingList = ["Eggs", "Milk"]

    Accessing and Modiftying an Array


    Array.count:配列の長さを検索する
    Array.isEmpty:配列が空かどうかを確認
    Array.append(:):配列の最後にアイテムを追加
    (+=)演算子で追加可能
    shopping List += ["Banking Poweder"]
    subscript構文を使用して配列から値を取得します.
    var firstItem = shoppingList[0]
    shoppingList[0] = "Six eggs"
    // index 0에 해당하는 value가 바뀜.
    shoppingList[4...6] = ["bananas","apples"]
    // range를 이용하여 값 변경. range의 길이와 대체 value set이 달라도 가능.
    挿入:Array.insert(_:at:)
    削除:Array.remove(at:)
    ->removeLast()を使用する場合は、インデックスを指定せずに最後の要素を削除します.
    shoppingList.insert("maple syrup", at : 0)
    // value를 at:index에 삽입.
    shoppingList.remove(at:0)
    // at:0에 해당하는 element 제거.

    interating Over an Array


    forinループでArrayでvalue setをチェックできます.
    for item in shoppingList{
    	print(item)
    }
    valueだけでなくindexもチェックする場合は、列挙()メソッドを使用します.
    for (index,value) in shoppingList.enumerated(){
    	print("Item \(index+1): \(value)")
    }

    Sets


    setには一定の順序はありません.アイテムをitem順序に関係なく保存したくない場合は、ArrayではなくSetsを使用します.

    Hash Values for Set Types


    Setに格納するためにはハッシュできる必要がある.ここで使用するハッシュ値はInt型です.すなわち、AとBが存在する場合、Aのハッシュ値とBのハッシュ値が同じであれば、AとBは同じである.
    すべてのSWIFTの基本タイプ(String、Int、Double、Bool)はハッシュ可能であり、setの値またはdictionaryのキー値であってもよい.

    Creating and Initailizing an Empty Set

    var letters = Set<Character>()
    print("letters is of type Set<Character> width \(letters.count) items")
    // Prints "letters is of type Set<Character> with 0 items.
    
    > letters 변수의 타입은 Set<Character> 선언으로 추론된다.
    SETが一度宣言して空のSETを与えても、SETの変数タイプは同じです.
    letters.insert("a")
    // letters now contains 1 value of type Characters
    letters = []
    // letters is now an empty set,but is still of type Set<Character>

    Creating a Set with an Array Literal


    配列を宣言するときにSetを宣言するときと同じように、初期値を設定できます.
    var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
    // favoriteGenres has been initialized with three initial items
    
    var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
    Setの変数タイプを書き込む必要がなく、初期宣言要素のタイプに設定できます.

    Accessing and Modifying a Set


    Arrayと同様にcount、insert、isEmptyがあります.
    contains(:):コレクションに特定の要素が存在するかどうかを確認します.
    if favoriteGenres.contains("Funk") {
        print("I get up on the good foot.")
    } else {
        print("It's too funky in here.")
    }
    // Prints "It's too funky in here.’
    return値はboolタイプとして表示されます.

    Iterating Over a Set


    Setの値はfor inループでチェックできます.
    for genre in favoriteGenres {
        print("\(genre)")
    }
    // Classical
    // Jazz
    // Hip hop
    Setには順序が定義されていません.「<」演算子を比較するには、ソート()メソッドを使用します.
    for genre in favoriteGenres.sorted() {
        print("\(genre)")
    }
    // Classical
    // Hip hop
    // Jazz

    Performing Set Operations


    集合、二次集合、交差、集合などとして使用できます.

    Fundamental Set Operating


  • 専門(:):交差
  • 対称差分(:):集合の繰返し値消去集合
  • union(:):合計
  • 減算(:):差分
  • 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 Membership and Equality



    集合aは、bのスーパーセット、bのすべての要素を含む.
    逆に、集合bはaのサブセットである.bのすべての要素はaに含まれている.
    集合bとcはdisjointである.交差していません.
    ==演算子を使用して、
  • の2つのセットのすべての値が同じかどうかを確認します.
  • 1つのコレクションのすべての値が別のコレクションに含まれていることを確認します.
  • isSuperset(of:)1つのセットが他のセットのすべての値を含むかどうかをチェック
  • isStrictSubset(of:)、isStrictSuperset(of:):2つのセットが異なり、サブセット、スーパーセットです.
  • isDiscoint(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

    Dictionary


    dictionaryは、同じタイプのキーと同じタイプの値の関係を格納します.
    Setのように順序は定義されていません.すべての価格はユニークです.

    Dictionary Type Shorthand Syntax


    Dictionaryまた、[Key:Value]を使用して操作を簡略化することもできます.

    Creating an Empty Dictionary

    var namesOfIntegers = [Int: String]() 
    // namesOfIntegers is an empty [Int: String] dictionary
    namesOfIntegers[16] = "sixteen" 
    // namesOfIntegers now contains 1 key-value pair 
    namesOfIntegers = [:] 
    // namesOfIntegers is once again an empty dictionary of type [Int: String]

    Creating a Dictionary with a Dictionary Literal


    Dictionary Literalを作成することもできます.
    var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
    var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
    //Dictionary 타입을 쓰지 않아도 type 자동 유추.

    Accessing and Modifying a Dicionary


    Array,Set同様count,isEmptyが利用可能である.
    subscript indexとしてkeyを使用して新しい値を割り当てるか、値を変更できます.
    airports["LHR"] = "London" 
    // the airports dictionary now contains 3 items
    airports["LHR"] = "London Heathrow"
    // the value for "LHR" has been changed to "London Heathrow"
    updateValue(:ofKey:):このキーがdictionaryに存在しない場合は、新しいキー/値が割り当てられ、キーが存在する場合は値が変更されます.
    上記のsubscriptとは異なり、update後に以前に保存した値が返され、optional typeが返されます.
    String valueが保存されている場合、String?orは「optional String」を返し、値が格納されていない場合はnilを返します.
    したがって、optional bindingで値を取得する必要があります.
    if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") { 
    	print("The old value for DUB was \(oldValue).") 
    } // Prints "The old value for DUB was Dublin."
    
    
    下付き構文も上記のように値を得ることができます.ただし、このキー値は存在しない可能性があるため、オプションbindingも使用する必要があります.
    if let airportName = airports["DUB"] { 
    	print("The name of the airport is \(airportName).") 
    } else { 
    	print("That airport is not in the airports dictionary.") 
    } 
    // Prints "The name of the airport is Dublin Airport."
    存在する鍵にnilを割り当てる場合は、削除できます.
    airports["APL"] = "Apple International" 
    // "Apple International" is not the real airport for APL, so delete it airports["APL"] = nil 
    // APL has now been removed from the dictionary
    removeValue(forkey:)を使用しても削除できます.対応するキーの値が存在する場合は削除された値を返し、値が存在しない場合はnilを返します.
    if let removedValue = airports.removeValue(forKey: "DUB"{ 
    	print("The removed airport's name is \(removedValue).") 
    } else { 
    	print("The airports dictionary does not contain a value for DUB.") 
    } 
    // Prints "The removed airport's name is Dublin Airport."

    Iterating Over a Dictionary


    foo-in loop:各項目戻り(key,value)tuple
    for (airportCode,airportName) in airports {
    	print("\(airportCode):\(airportName)")
    }
    // LHR : London Heathrow
    // YYZ : Toronto Pearson
    Dictionaryのkeyとvalue propertyにそれぞれアクセス可能
    for airportCode in airports.keys{
    	print("Airport Code : \(airportCode)")
    }
    // Airport code : LHR
    // Airport code : YYZ
    
    for airportName in airports.values{
    	print("Airport name : \(airportName)")
    }
    // AirportName : London Heathrow
    // AirportName : Toronto Pearson
    鍵と値はArrayインスタンスからアクセスできます.
    let airportCodes = [String](airports.keys)
    let airportNames = [String](airports.values)
    順序が定義されていないため、sorded()ソートを使用します.