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

强颜欢笑 提交于 2020-02-26 05:46:04
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]!)

    }

}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!