【问题标题】:Make an array from values belonging to a specific key in a dictionary (Swift 4)从属于字典中特定键的值创建一个数组(Swift 4)
【发布时间】:2017-07-21 22:37:10
【问题描述】:

我正在尝试使用 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) 不起作用。有人知道这将如何工作吗?

【问题讨论】:

  • database[author] 返回一个可选项,您必须将其解包。这似乎是少数可以接受强制展开的情况之一
  • 考虑在Collection上写一个扩展,给你一个随机元素;那么你只需要说let (author, quotes) = database.randomElement(); let quote = quotes.randomElement() :)

标签: swift dictionary random key


【解决方案1】:

randomQuote 中有很多小问题需要修复。

不需要第二次使用Array(...)

database[someKey] 已经为您提供了引号数组。

您还有一些不需要的括号。

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

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 
    let quoteArray = database[author]!

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

    print(author)
    print(quote)
}

【讨论】:

  • 谢谢,确实不需要第二次使用Array(...) 但是,我相信第一次使用它是必要的,这样才能无错误地运行此代码。没有它,它会将 LazyMapCollection 存储到变量中,当我尝试 .count 它时,这会给我带来问题。或者你有什么解决方法?
  • 是的,我的错。您确实需要第一次使用Array。我更新了我的答案。
【解决方案2】:

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

let quoteArray = database[author]!

旁注:不必要的时候用括号括起来会让人困惑,因为它看起来像一个元组。

【讨论】:

  • 是的,我知道这是不正确的,这只是一个错误的猜测。感谢您指出它是如何工作的。顺便说一句,他们在 swift 书的哪一页上写了关于在字典中使用 ! 的内容。我似乎找不到任何关于它的信息。
  • 它与字典无关,它是一种强制解包可选的方法。从字典中获取一个值会返回一个可选值,所以你必须打开它才能使用。
猜你喜欢
  • 1970-01-01
  • 2018-01-30
  • 2012-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-05
  • 2021-04-17
  • 1970-01-01
相关资源
最近更新 更多