Swift 笔记(十)

前端之家收集整理的这篇文章主要介绍了Swift 笔记(十)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我的主力博客半亩方塘

Dictionaries


1、A dictionary is an unordered collection of pairs,where each pair is comprised ofa keyanda value. The same key can’t appear twice in a dictionary,but different keys may point to the same value.All keys have to be of the same type,and all values have to be of the same type.

2、When you create a dictionary,you can explicitly declare the type of the keys and the type of the values:

let pairs: Dictionary<String,Int>

Swift can also infer the type of a dictionary from the type of the initializer:

let inferredPairs = Dictionary<String,Int>()

Or written with the preferred shorthand:

let alsoInferredPairs = [String: Int]()

Within the square brackets,the type of the keys is followed bya colonand the type of the values. This is the most common way to declare a dictionary.

If you want to declare a dictionary with initial values,you can use a dictionary literal. This is a list of key-value pairs separated by commas,enclosed in square brackets:

let namesAndscores = ["Anna": 2,"Brian": 2,"Craig": 8,"Donna": 6]
print(namesAndscores)
// > ["Brian": 2,"Anna": 2,"Donna": 6]

In this example,the dictionary has pairs of[String: Int]. When you print the dictionary,you seethere’s no particular order to the pairs.

An empty dictionary literal looks like this:[:].You can use that to empty an existing dictionary like so:

var emptyDictionary: [Int: Int]
emptyDictionary = [:]


3、Dictionaries support subscripting to access values. Unlike arrays,you don’t access a value by its index but rather by its key. For example,if you want to get Anna’s score,you would type:

print(namesAndscores["Anna"])
// > Optional(2)

Notice that the return type is an optional. The dictionary will check if there’s a pair with the key “Anna”,and if there is,return its value. If the dictionary doesn’t find the key,it will return nil:

print(namesAndscores["Greg"])
// > nil

Properties and methods:

print(namesAndscores.isEmpty)
// > false
print(namesAndscores.count)
// > 4

print(Array(namesAndscores.keys))
// > ["Brian","Anna","Craig","Donna"]
print(Array(namesAndscores.values))
// > [2,2,8,6]

4、Take a look at Bob’s info:

var bobData = ["name": "Bob","profession": "Card Player","country": "USA"]

Let’s say you got more information about Bob and you wanted to add it to the dictionary. This is how you’d do it:

bobData.updateValue("CA",forKey: "state")

There’s even a shorter way,using subscripting:

bobData["city"] = "San Francisco"

You want to change Bob’s name from Bob to Bobby:

bobData.updateValue("Bobby",forKey: "name"]
// > Bob

Why does it return the string “Bob”?updateValue(_:forKey:)replaces the value of the given key with the new value andreturns the old value. If the key doesn’t exist,this method willadd a new pairand returnnil.

As with adding,you can change his profession with less code by using subscripting:

bobData["profession"] = "Mailman"

Like the first method,the code updates the value for this key or,if the key doesn’t exist,creates a new pair.

You want to remove all information about his whereabouts:

bobData.removeValueForKey("state")


As you might expect,there’s a shorter way to do this using subscripting:

bobData["city"] = nil

Assigningnilas a key’s associated value removes the pair from the dictionary.

5、Thefor-inloop also works when you want to iterate over a dictionary. But since the items in a dictionary are pairs,you need to use tuple:

for (key,value) in namesAndscores {
    print("\(key) - \(value)")
}
// > Brian - 2
// > Anna - 2
// > Craig - 8
// > Donna - 6

It’s also possible to iterate over just the keys:

for key in namesAndscores.keys {
    print("\(key),",terminator: "")  // no newline
}
print("") // print one final newline
// > Brian,Anna,Craig,Donna,

You can iterate over just the values in the same manner with thevaluesproperty on the dictionary.

6、You could usereduce(_:combine:)to replace the prevIoUs code snippet with a single line of code:

let namesString = namesAndscores.reduce("",combine: { $0 + "\($1.0)," })
print(namesString)

In a reduce statement,$0refers to the partially-combined result,and$1refers to the current element. Since the elements in a dictionary are tuples,you need to use$1.0to get thekeyof the pair.

Let’s see how you could usefilter(_:)to find all the players with a score of less than 5:

print(namesAndscores.filter({ $0.1 < 5 }))
// > [("Brian",2),("Anna",2)]

Here you use$0.1to access thevalueof the pair.

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

猜你在找的Swift相关文章