【问题标题】:How do I get an item with subelements from an array in Swift? [duplicate]如何从 Swift 中的数组中获取包含子元素的项目? [复制]
【发布时间】:2018-11-20 05:17:42
【问题描述】:

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

我想一次显示一个随机报价。当用户刷新屏幕时,他们会得到另一个报价。当我将.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)
]

【问题讨论】:

  • 仅供参考-您不应该将所有这些数据都放入代码中。将其存储在文件或数据库中,并在运行时加载您需要的内容。

标签: arrays swift loops


【解决方案1】:

您可以扩展 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()

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

【讨论】:

  • 太棒了!非常感谢您的帮助!
  • 不,不要考虑使用元组。 Quote 的结构是正确的方法,而不是元组。
猜你喜欢
  • 2021-09-11
  • 2015-09-07
  • 2012-11-09
  • 2021-10-21
  • 2019-12-17
  • 1970-01-01
  • 1970-01-01
  • 2014-05-26
  • 1970-01-01
相关资源
最近更新 更多