swit开发Dictionary详细使用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swit开发Dictionary详细使用相关的知识,希望对你有一定的参考价值。
//
// ViewController.swift
// Swift+Dictionary
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.yellow;
//创建一个空数组
let dic1 = [Int: String]()
print(dic1)
//创建数组,key为int型,value为string型
var dic2:[Int:String] = [1:"one",2:"two", 3:"three"]
print(dic2)
let dict3 = ["name":"DevZhang", "job":"iosDev", "company":"VSTECS"]
print(dict3)
//访问字典
let value1 = dic2[1];
print(value1)
let value2 = dict3["name"]
print(value2)
//添加数据
let value3 = dic2.updateValue("Four", forKey: 4)
//或者是dict2[4] = "Four"
print(value3)
print(value2)
//修改字典
//方法1 使用updatevalue(forkey:)增加或更新字典的内容.如果key不存在,则添加值,如果存在则修改key对应的值.格式为:dict.updatevalue(value,forkey:key)方法返回optional值
var value4 = dic2.updateValue("TwoTmp", forKey: 2);
print(dic2)
print(value4)
//方法2:通过指定的key来修改字典的值
var value5 = dic2[3];
print(value5)
value5 = "ThreeTmp"//次修改方法无效
print(dic2)
dic2[3] = "ThreeTmp"//此修改有效
print(dic2)
//移除key-value对
//1:使用removevalueforkey() 方法来移除字典key-value 对,如果key存在该方法返回移除的值,如果不存在返回nil.
let valueRemove1 = dic2.removeValue(forKey: 2)
print(valueRemove1)
print(dic2)
//通过指定键的值为nil来移除key-value(键-值)对
dic2[1] = nil
print(dic2)
//遍历字典
//1:使用for-in循环来遍历某个字典中的键值对
for (key,value) in dict3 {
print("字典 key \(key) - 字典 value\(value)")
}
//2:使用enumerate()方法来进行字典遍历,返回的是字典的索引及(key, value)对
for (key, value) in dict3.enumerated() {
print("字典 key \(key) - 字典(key,value) 对\(value)")
}
//3:
for key in dict3.keys {
let value = dict3[key]
print("key = \(key),value = \(value)")
}
//字典转化为数组
//提取字典的键值(key-value)对,并转换为独立的数组
let dictkeys = [String](dict3.keys)
for (key) in dictkeys {
print("\(key)")
}
let dictValues = [String](dict3.values)
for (value) in dictValues {
print("\(value)")
}
//isEmpty 属性
let empty1 = dic1.isEmpty
print("dic1 is \(empty1)")
let empty2 = dict3.isEmpty
print("dict3 is \(empty2)")
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
以上是关于swit开发Dictionary详细使用的主要内容,如果未能解决你的问题,请参考以下文章