arrays - 如何从 Swift 中的数组中获取包含子元素的项目?
问题描述
我有一个引号类,其中包含一个充满引号的数组。下面的代码显示了两个。每条引文都有作者、出处和布尔值,用于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)
]
解决方案
您可以扩展 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()
附带说明,由于您正在处理固定/静态内容/结构,请考虑使用元组来存储引用
推荐阅读
- redis - 查看 Redis PubSub 通道的值
- python - 导入模块所需的模块
- jquery - 菜单项和内容问题
- css - 日期的宽度不一样,因为数字 1 和 2 的宽度不同?
- android - 使用 FirebaseJobDispatcher
- javascript - 从由 javascript 函数创建的表单提交 FormData 到 php
- elasticsearch - Elasticsearch 查询错误 - [或] 查询格式错误,查询名称后没有 start_object
- math - 飞镖乘法
- vb.net - 如果父列或子列不在数据集中,则无法创建 DataRelation
- python - Python-Tkinter:TypeError:“NoneType”对象不可下标