Swift3 – Dictionaryを扱う
環境
- Dictionary
- Swift
- Swift3
- Xcode
- Xcode9
説明
ディクショナリーを使うとキーと値で Key-Value データを扱うことができます。
実装
//
// ViewController.swift
// void-swift3
//
// Created by ryosuke-hujisawa on 2017/11/03.
// Copyright © 2017年 ryosuke-hujisawa. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
/*
Stringをキーにしてディクショナリーを初期化
*/
var DictionaryAny: Dictionary<String, Any> = [:]
var DictionaryUIView: Dictionary<String, UIView> = [:]
var DictionaryInt: Dictionary<String, Int> = [:]
/*
Intをキーにしてディクショナリーを初期化
*/
var AnyDictionary: Dictionary<Int, Any> = [:]
var UIViewDictionary: Dictionary<Int, UIView> = [:]
var IntDictionary: Dictionary<Int, Int> = [:]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
/*
ディクショナリーにキーと値を代入
*/
DictionaryAny = ["文字列1をキーにする": "値は文字列"]
DictionaryUIView = ["文字列2をキーにする": UIView.init(frame: CGRect.init(x: 0, y: 0, width: 250, height: 250))]
DictionaryInt = ["文字列3をキーにする": 10]
AnyDictionary = [1: "値は文字列"]
UIViewDictionary = [2: UIView.init(frame: CGRect.init(x: 0, y: 0, width: 250, height: 250))]
IntDictionary = [3: 10]
/*
ディクショナリーを出力
*/
print( DictionaryAny["文字列1をキーにする"]! )
print( DictionaryUIView["文字列2をキーにする"]! )
print( DictionaryInt["文字列3をキーにする"]! )
print( AnyDictionary[1]! )
print( UIViewDictionary[2]! )
print( IntDictionary[3]! )
/*
//結果
値は文字列
<UIView: 0x7f7fd2f0a630; frame = (0 0; 250 250); layer = <CALayer: 0x60000003de60>>
10
値は文字列
<UIView: 0x7f7fd2f0a810; frame = (0 0; 250 250); layer = <CALayer: 0x60000003de80>>
10
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}