首页 > 解决方案 > 如何从 Swift 中的数组中获取包含子元素的项目?

问题描述

我有一个引号类,其中包含一个充满引号的数组。下面的代码显示了两个。每条引文都有作者、出处和布尔值,用于hasSeenhasSaved

我想一次显示一个随机报价。当用户刷新屏幕时,他们会得到另一个报价。当我放入.randomElement()!数组并打印结果时,我得到appName.Quote.

有没有办法从这个数组中访问随机报价?我希望能够向最终用户显示文本和归属。

var quotes:[Quote] = [
    Quote(
        quoteText: "The only way to make sense out of change is to plunge into it, move with it, and join the dance.",
        quoteAttribution: "Alan Watts",
        hasSeen: false,
        hasSaved: false),
    Quote(
        quoteText: "Luck is what happens when preparation meets opportunity.",
        quoteAttribution: "Seneca",
        hasSeen: false,
        hasSaved: false)
]

标签: arraysswiftloops

解决方案


您可以扩展 swift 的 Array 以具有此功能:

extension Array {
    func randomItem() -> Element? {
        if isEmpty { return nil }
        let index = Int(arc4random_uniform(UInt32(self.count)))
        return self[index]
    }
}

您可以像这样访问随机报价:

let quote = quotes.randomItem()

附带说明,由于您正在处理固定/静态内容/结构,请考虑使用元组来存储引用


推荐阅读