学习笔记: 100 Days of SwiftUI_Day 3_Dictionary

相比于Array需要按照顺序获取内容,Dictionary有一个专门的key来获取相对应的数值。

1. Syntax

full :  Dictionary<key, value>   

shorthand:  [key: value]

2. Creating

var namesOfIntegers: [Int: String] = [ : ] //创建一个空的dictionary,类型为[Int: String]

var namesOfIntegers: [Int: String] = [1:"lsfj",2:"fjaiejf"]

var namesOfIntegers = [1:"lsfj",2:"fjaiejf"] //这条和上面一条等同

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

3. Accessing and Modifying

Dictionary也有很多属性和方法,很类似于Array,具体的可以阅读Xcode->help->developer Documentation中的相关内容。下面列出了常见的几个

先创建一个dictionary,以下代码都用的这个var。

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

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

isEmpty

if airports.isEmpty {

    print("The airports dictionary is empty.")

}

add a new item

airports["LHR"] = "London"

change the value by subscript syntax

airports["LHR"] = "London Heathrow"

change the value by updataValue method

if let oldValue = airports.updateValue("Dubling Airport", forKey: "DUB") {

    print("The old value for DUB was \(oldValue)")

} else{

    print("There was no value for key DUB")

}

retrieve a value by subscript syntax

if let aiportName = airports["DUB"] {

    print("The name of the airport is \(aiportName)")

} else {

    print("That airport isn't in the airport dictionary")

}

remove a key-value pair by subscript syntax

airports["APL"] = "Apple International"

airports["APL"] = nil

remove a key-value pair by removeValue

if let removeValue = airports.removeValue(forKey: "DUB") {

    print("The removed aireport's name is \(removeValue) .")

} else {

    print("The airports dictionary doesn't contain a value for DUB.")

}

get a dictionary's keys or values

let airportCodes = [String](airports.keys)

let airportNames = [String](airports.values)

4. Iterating Over a Dictionary

keys 和 values 都需要的时候

for (airportCode, airportName) in airports {

    print("\(airportCode): \(airportName)")

}

只需要keys时

for airportCode in airports.keys {

    print("Airport Code: \(airportCode)")

}

只需要values时

for airportName in airports.values {

    print("Airport Name: \(airportName)")

}

5. Default Value

获取dictionary中的值得时候有时候会返回nil,当你不想要这样的返回值而是想要给没有的key一个默认值时可以这样写

let airportName = airports["DDR", default: "nothing"]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值