×

通过键值获取字典的对应的值时,返回的值是optional类型的

Falcon 2020-02-03 views:
自动摘要

正在生成中……

let studentsAndscores = ["Amy": 88, "James": 55, "Helen": 99]
 
Then your function should print 99.
 
But you don't know what the scores are, so your program has to handle all possibilities!
 
Hint: When you get the value out of a dictionary using a key, the value that comes out is an Optional!
 
也就是说此时你需要用 let amyScore = studentsAndscores["Amy"]!  解包为Int类型的值 ,然后才能进行比较。
 
另一个示例:

class ViewController: UIViewController {        

    let eggTime:[String: Int] = [

        "Soft":5,

        "Medium":7,

        "Hard":12        

    ]

    @IBAction func hardnessSelected(_ sender: UIButton) {

        print(sender.currentTitle!)        

        let hardness = sender.currentTitle!

        print(eggTime[hardness]!)

    }

}