79
78

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Swift] Dictionaryをこねくり回すネタ集

Last updated at Posted at 2017-08-02

Dictionaryの特徴

  • keyはhashable(比較可能)なデータタイプでないといけない。
  • valueのデータタイプはなんでもOK
  • Dictionary内のvalueデータタイプは全部同じじゃないといけない
  • 順番はランダム / 考慮されない

初期化

値が最初nilの場合

.swift
var nameOfIntegers = [Int:String]()

//or

var nameOfIntegers:[Int:String] = [:]
nameOfIntegers[16] = "sixteen"
print(nameOfIntegers)//[16: "sixteen"]

値がある場合

.swift
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

// or

var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

*Valueには他のコレクションタイプも入れられる!

.swift
let dictionary = [
   "A" : [1, 2],
   "Z" : [3, 4],
   "D" : [5, 6]
]

データ取得・保存

基本的なメソッドはArray とセットと同じ(count, isEmptyなど)

count

Dictionaryのデータ数を返す

.swift
 print("The airports dictionary contains \(airports.count) items.")
// "The airports dictionary contains 2 items."

isEmpty

Dictionary の中身があるかどうか判定する。

.swift
if airports.isEmpty {
    print("The airports dictionary is empty.")
} else {
    print("The airports dictionary is not empty.")
}
 // Prints "The airports dictionary is not empty."

Add + Override

追加と上書きは同じように書きます。(ArrayとSetも同じ)

practice.swift
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

//keyがないので、追加される
airports["LHR"] = "London"

//keyはあるので、Valueを上書きする
airports["YYZ"] = "Vancouver"
        
print(airports)
// ["DUB": "Dublin", "LHR": "London", "YYZ": "Vancouver"]

*keyが存在している時だけに上書きしたい場合は、

.swift
var airport = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
if (airport["YVR"] != nil){
  airport["YVR"] = "Vancouver"
}
        
print("airport: \(airport)") // airport: ["DUB": "Dublin", "YYZ": "Toronto Pearson"]

ValueとKeyだけをプリントする

.swift
let airportCodes = [String](airports.keys)
// airportCodes is ["YYZ", "LHR"]
     
let airportNames = [String](airports.values)
// airportNames is ["Toronto Pearson", "London Heathrow"]

Keyを探してValueを取得する

返り値はOptionalなのでunwrapが必要です。

.swift
var airport = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

if let yyz = airport["YYZ"]{
   print(yyz)//Toronto Pearson
}

Valueを探してKeyを取得する

ValueがArrayだった場合,ArrayのメンバーからKeyを取得する方法

StackOverFlowで見つけたのがいいなと思ったので、メモ!

.swift
func findKeyForValue(value: Int, dictionary: [String: [Int]]) ->String?
{
    for (key, array) in dictionary
    {
        if (array.contains(value))
        {
            return key
        }
    }

    return nil
}

取得方法↓

.swift
let kids = ["Toddlers": [0, 1, 2],
        "KinderGarden" :[3, 4, 5]]

print(self.findKeyForValue(1, dictionary: kids))

for loop

こう書くと、keyとvalueが同時に取れます。

var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]

for (key, value) in companies {
    println("\(key) -> \(value)")
}

Sort

Dictionaryをソートする(keyがメインでソートされますが)

.swift

let dictionary = [
   "A" : 9, "Z" : 3, "D" : 6, "O" : 12
]
        
let sortedDic = dictionary.sorted() { $0.0< $1.0 }
print(sortedDic)//[(key: "A", value: 9), (key: "D", value: 6), (key: "O", value: 12), (key: "Z", value: 3)]

Keyをソート

.swift
let sortedKeys = Array(dictionary.keys).sorted(by: <)
print(sortedKeys)//["A", "D", "O", "Z"]

Valueをソート

.swift
let fruitsDict = ["apple": 5, "pear": 9, "grape": 1]
let fruitsTupleArray = fruitsDict.sorted{ $0.value > $1.value }
        
print(fruitsTupleArray) // [(key: "pear", value: 9), (key: "apple", value: 5), (key: "grape", value: 1)]

ValueがArrayだった場合、複数のソートをこなす。

.swift
var items = [Int: [String]]()
        
items[0] = ["Apple","/image/apple.png","29"]
items[1] = ["AAA","/image/aaa.png","29"]
items[2] = ["Banana","/image/banana.png","29"]
        
let itemResult = items.sorted { (first: (key: Int, value: [String]), second: (key: Int, value: [String])) -> Bool in
            return first.value.first! < second.value.first!
        }
        
print (itemResult)
//[(key: 1, value: ["AAA", "/image/aaa.png", "29"]), (key: 0, value: ["Apple", "/image/apple.png", "29"]), (key: 2, value: ["Banana", "/image/banana.png", "29"])]

とりあえずここまで!

もっと載せていく予定です〜。

79
78
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
79
78

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?