[Swift] Collection Type - Dictionary

10994 ワード

📕 Dictionary



数式図
Dictionaryは、KeyとValue形式でデータを格納するコンテナです.
Arrayとの最大の違いは順序が保障されていないことです.
各値は、一意のキー値に関連付けられます.
Key値はDictionaryでvalueを検索する識別子として機能します.
(会員情報では、身分証明書番号はKey、氏名またはその他の情報はValueとすることができる.)
鍵の値は譲渡可能である必要があります.つまり、それ自体が唯一表現できるものでなければなりません.
SWIFTのエントリーレベル(Int、String、Float...)基本的には使えるので、Dictionaryの鍵としても使えます.

作成

var dic1 : [Int : String] = [:]
var dic2 = [Int : String]()
var dic3 : Dictionary = [Int:String]()
var dic4 : Dictionary<Int, String> = Dictionary<Int, String>() // 👍
var myMenu : Dictionary<String, Int> = ["Americano":3200, "Latte":3700]
どちらかを知るだけで使えますので、問題ありません!

作成&初期化

var myMenu1 : Dictionary<String, Int> = ["Americano":3200, "Latte":3700]
var myMenu2 : Dictionary = ["Americano":3200, "Latte":3700]
var myMenu3 : [String : Int] = ["Americano":3200, "Latte":3700]
var myMenu4 = ["Americano":3200, "Latte":3700] // 타입 추론
myMenu4類型推論で[String:Int]Dictionaryとわかる.
また,ディクショナリには順序がないため,順序が保障されていないことが確認できる.

データの変更


キー値が分かれば、Valueを変更できます.
  • dictionaryName[Key] = NewValue:該当鍵の値をNew Valueに変換します.
  • func updateValue(Value, forKey: Key) -> Value?
  • このときKey存在するはずの鍵です.
  • var lectures : Dictionary<String, String> = ["CSE1294":"Python", "CSE3928":"Computer Architecture"]
    print(lectures) 
    //["CSE3928": "Computer Architecture", "CSE1294": "Python"]
    
    lectures["CSE3928"] = "Operating System"
    print(lectures)
    //["CSE3928": "Operating System", "CSE1294": "Python"]
    
    lectures.updateValue("Machine Learning", forKey: "CSE3928")
    print(lectures)
    //["CSE3928": "Machine Learning", "CSE1294": "Python"]
    

    データの追加

  • func updateValue(Value, forKey: Key) -> Value?
  • このときKey既存には存在しないはずの鍵です.
  • lectures.updateValue("Computer Vision", forKey: "CSE3201")
    // Print ["CSE3928": "Machine Learning", "CSE1294": "Python", "CSE3201": "Computer Vision"]

    アクセス⚠▼値


    アクセスバリューは前にデータ修正で見たようにDictionaryName[Key]特に,SWIFTの立場から,鍵に対するValueが存在するかどうかは不明であるため,ValueをOptional形式に変換する.
    したがって、値を使用する場合!(Unwrapping,Unrapping)で値段を出します.
    print(lectures["CSE3928"])
        //Print Optional("Machine Learning")
    print(lectures["CSE3928"]!) // 언래핑
        // Print Machine Learning
    

    値の削除

  • removeValue(forKey:)
  • removeAll(_:)
  • lectures.removeValue(forKey: "CSE3928")
    lectures.removeAll()