Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active June 14, 2016 11:32
Show Gist options
  • Save KentarouKanno/bc5c85bafc2c1be7b905 to your computer and use it in GitHub Desktop.
Save KentarouKanno/bc5c85bafc2c1be7b905 to your computer and use it in GitHub Desktop.
Dictionary

Dictionary

★ 辞書のkeyとなれるのはHashableプロパティに準拠した型のみ
HashableはEquatableを継承している必要がある

public struct Dictionary<Key : Hashable, Value> : CollectionType, DictionaryLiteralConvertible { ... }

・Bool
・CGFloat
・COpaquePointer
・Character
・Double
・Float
・Int
・Int16
・Int32
・Int64
・Int8
・NSObject
・ObjectIdentifier
・Selector
・Set
・String
・UInt
・UInt16
・UInt32
・UInt64
・UInt8
・UnicodeScalar
・UnsafeMutablePointer
・UnsafePointer

★ NSObjectのkey

class Obj: NSObject {
    var name: String = ""
}

var obj1 = Obj()
var obj2 = Obj()

// 型推論でもOK
var dict: [NSObject: String] = [obj1: "a", obj2: "b"]

var value = dict[obj1]

★ 初期化

var dict: Dictionary<String, String> = [:]
var dict: [String: String] = [:]

// "key":"value"
var dict = ["key1":"value1","key2":"value2","key3":"value3"] 

// -------------------

let dictionary: Dictionary<String, Int> = ["a": 1, "b": 2, "c": 3]

let dictionary: [String: Int] = ["a": 1, "b": 2, "c": 3]

let dictionary: Dictionary = ["a": 1, "b": 2, "c": 3]

let dictionary = ["a": 1, "b": 2, "c": 3]

★ キーを指定して値を追加する

// keyが無ければ新しく追加され、あれば上書きされる
dict["key4"] = "value4"
//=> ["key1": "value1", "key4": "value4", "key2": "value2", "key3": "value3"]


dict["key1"] = "abc"
//=> ["key1": "abc", "key4": "value4", "key2": "value2", "key3": "value3"]

// 上記と同じ
dict.updateValue("abc", forKey: "key1")

★ キーを指定して値を取り出す

var value = dict["key1"]
//=> "value1"

★ キーを指定して値を削除する

dict["key1"] = nil

// 削除した値がreturnされる
var deleteVale = dict.removeValueForKey("key1")
//=> "value1"

★ 要素を全て削除する

dict.removeAll()
//=> [:]

dict = [:]

★ 辞書の最初のキー&値のタプルを取り出す(取り出す順番は順不同)

// Optionalのタプルで取得できる
var keyValue = dict.first
//=> "Optional(("key1", "value1"))"

var key = keyValue.first!.0
//=> "key1"
var value = keyValue.first!.1
//=> "value1"

★ 格納している要素数を返す

var num = dict.count
//=> 3

★ keyとvalueを両方取り出す

for(key,value) in dict {
    print("key = \(key),value = \(value)")
}

//=> 
key = key1,value = value1
key = key2,value = value2
key = key3,value = value3

★ keyのみを取り出し

for key in dict.keys {            
    print(key)
}

// keyの配列を取得
var keyArray = [String](dict.keys)
var keyArray = Array(dict.keys)
//=> ["key1", "key3", "key2"]

★ valueのみを取り出す

for value in dict.values {
    print(value)
}

// valueの配列を取得
var valueArray = [String](dict.values)
var valueArray = Array(dict.values)
//=> ["value1", "value3", "value2"]

★ Dictionary -> NSDictionary

var dict = ["key1": "value1", "key2": "value2"]
dict.dynamicType
//=> Dictionary<String, String>.Type

var nsdicionary: NSDictionary = NSDictionary(dictionary: dict)
nsdicionary.dynamicType
//=> __NSDictionaryI.Type

★ NSDictionary -> Dictionary

var nsdicionary: NSDictionary = NSDictionary(dictionary: ["key1": "value1", "key2": "value2"])
nsdicionary.dynamicType
//=> __NSDictionaryI.Type

var dict = nsdicionary as Dictionary
dict.dynamicType
//=> Dictionary<NSObject, AnyObject>.Type

print(dict["key1"])
//=> Optional(value1)

// ----------------------

var dict: Dictionary<String, String> = nsdicionary as! Dictionary
dict.dynamicType
//=> Dictionary<String, String>.Type

print(dict["key1"])
//=> Optional(value1)

★ Array -> Dictionary (Index付き)

let array = ["Apple", "Google", "Yahoo", "Facebook"]


let dic = array.enumerate().reduce ([String: Int]()) { (dict, val) in
    var dict = dict
    dict[val.element] = val.index
    return dict
}

dic
//=> [["Apple": 0], ["Google": 1], ["Yahoo": 2], ["Facebook": 3]]


dic["Google"]
//=> 1

簡単なJSON解析

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 変換する型を定義 ※AnyObject型が無い場合は全て記述できる
        typealias JSONType = [String: [String: [String: String]]]
        
        
        let path = NSBundle.mainBundle().pathForResource("English", ofType: "plist")
        let dict = NSDictionary(contentsOfFile: path!)
        print("型変換前 : ",dict)
        
        
        let dictionary = NSDictionary(contentsOfFile: path!) as! JSONType
        print("型変換後 : ",dictionary)
        
        for (_, letters) in dictionary {
            for (letter, words) in letters {
                print("[\(letter)]")
                for (en, ja) in words {
                    print("\(en)=\(ja)")
                }
            }
        }
    }
}


/*  出力
型変換前 :  Optional({
    Word =     {
        A =         {
            And = "\U540c\U3058";
            Answear = "\U7b54\U3048";
        };
        D =         {
            Dog = "\U72ac";
        };
    };
})
型変換後 :  ["Word": ["A": ["And": "同じ", "Answear": "答え"], "D": ["Dog": "犬"]]]
[A]
And=同じ
Answear=答え
[D]
Dog=犬
*/
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>Word</key>
	<dict>
		<key>A</key>
		<dict>
			<key>Answear</key>
			<string>答え</string>
			<key>And</key>
			<string>同じ</string>
		</dict>
		<key>D</key>
		<dict>
			<key>Dog</key>
			<string>犬</string>
		</dict>
	</dict>
</dict>
</plist>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment