根据属于字典中特定键的值创建数组(Swift 4)

时间:2017-07-21 22:37:11

标签: swift dictionary random key

我正在使用Swift 4中的字典进行实验。我正在尝试使用属于字典中随机选择的键的几个值来创建数组。我不确定在Swift 4中我需要做什么。

//: Dictionary Test 

import UIKit

var database = ["Albert Einstein": ["Alberts first quote",
                                    "Alberts second quote",
                                    "Alberts third quote"],

                     "Martin Luther King": ["Martin's first quote",
                                            "Martin's second quote",
                                            "Martin's third quote"],

                     "Newton": ["Newton's first quote",
                                "Newton's second quote",
                                "Newton's third quote"]]

func randomQuote(){
    //Make an array from database keys
    var authorArray = Array(database.keys)

    //Pick a random author
    let author = (authorArray[Int(arc4random_uniform(UInt32(authorArray.count)))])

    //Make an array from values based on the author we've picked (HERE'S THE PROBLEM)
    let quoteArray = Array(database[author].values)

    //Pick a random quote from the choses author
    let quote = (quoteArray[Int(arc4random_uniform(UInt32(quoteArray.count)))])

    print(author)
    print(quote)
}

randomQuote()

现在显然let quoteArray = Array(database[author].values)无效。任何人都知道这将如何运作?

2 个答案:

答案 0 :(得分:1)

<ul> <li><a class="soc" href="some-link-here" target="_blank"></a></li> <li><a class="soc" href="some-other-link-here" target="_blank"></a></li> <li><a class="soc" href="another-link-here" target="_blank"></a></li> </ul>中有很多小事需要修复。

不需要第二次使用randomQuote

Array(...)已经为您提供了引号数组。

你还有一些你不需要的额外括号。

这里是包含所有修复程序的更新代码:

database[someKey]

答案 1 :(得分:0)

database [author]是一个数组,而不是字典。你需要这样做:

let quoteArray = database[author]!

旁注:当不必要时,parens周围的东西会让人感到困惑,因为它会让它看起来像一个元组。