Swift学习:8.字典

前端之家收集整理的这篇文章主要介绍了Swift学习:8.字典前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

字典

字典是一种存储多个相同类型的值的容器。每个值(value)都关联唯一的键(key),键作为字典中的这个值数据的标识符。和数组中的数据项不同,字典中的数据项并没有具体顺序。

1.初始化

var games: [String:String] = [“Diablo3”:”2014:8:12”,
“Dragon Age”:”2014:10:07”]
var games = [“Diablo3”:”2014:8:12”,“DragonAge”:”2014:10:07”]
games[“LittleBigPlanet3”] = “2014:11:29"
games[“LittleBigPlanet3”] = “2014:11:30"
var nameOfIntegers = [Int:String]()
namesOfIntegers[16] = “sixteen"
namesOfIntegers = [:]

2.修改已有键值:

if let oldValue = games.updateValue(“2014:8:14”,forKey:”Diablo3”){
println(“Diablo3的旧值:\(oldValue)”)
}

3.获取键值为可选类型:

if let releaseDate = games[“Diablo3”]{
println(“该游戏的发布日期是\(releaseDate)”)
}else {
println(“该游戏的发布日期不在games字典里”)
}
games[“LittleBigPlanet3”] = nil 移除键值
games.removeValueForKey(“Diablo3”) 和updateValue一样

4.字典遍历

let airports = [“TYO”:”Tokyo”,”LHR”:”London”]
for (airportCode,airportName) in airports{
println(“\(airportCode): \(airportName)”)
}
for airportCode in airports.keys{}
for airportNameinairports.values{}

5.示例代码

var airports:Dictionary<String,String> = ["TKO":"Tokyo","CHA":"China"]

println("the airports Dictionary has \(airports.count) airport")

airports["LON"] = "London"

airports["LON"] = "London weather"

airports["CHA"] = nil

if let oldValue = airports.updateValue("Dublin",forKey: "CHA"){

println("the old value is \(oldValue)")

}else{

println("there is no airport named CHA")

}

for (airportNumber,airportName) in airports{

println("airportNumber:\(airportNumber) airportName:"+airportName)

}

for key in airports.keys{

}

for value in airports.values{

}

let airportCode = Array(airports.keys)

var nameOfIntergers = Dictionary<String,Int>()

nameOfIntergers = [:]

原文链接:https://www.f2er.com/swift/327165.html

猜你在找的Swift相关文章