swift - 如何在 Swift 中访问字典中的随机元素

标签 swift dictionary random

我得到了以下代码:

var myDic = [String: Customer]()
let s1 = Customer("nameee", "email1")
let s2 = Customer("nameee2", "email2")
let s3 = Customer("nameee3", "email3")
myDic[s1.name] = s1
myDic[s2.name] = s2
myDic[s3.name] = s3

如何从字典中随机选择一个元素?我想我应该使用 arc4random_uniform 但找不到任何相关文档。

最佳答案

你必须四处转换一些东西,但这似乎有效。

var dict:[String:Int] = ["A":123, "B": 234, "C": 345]
let index: Int = Int(arc4random_uniform(UInt32(dict.count)))
let randomVal = Array(dict.values)[index] # 123 or 234 or 345

基本上,生成一个介于零和项目总数之间的随机索引值。获取字典的值作为数组,然后获取随机索引。

您甚至可以将其包装在扩展程序中以便于访问。

关于swift - 如何在 Swift 中访问字典中的随机元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25456047/

相关文章:

random - 保存程序生成的所有随机数,然后在 Racket 中重复使用它们

ios - 静态工具操作的静态类与静态结构?

Java,更新 map

ios - 选择器 View 未更新

c# - 用于类型化字典类型的 CodeDom InitExpression

Python获取具有最高属性值的嵌套字典的键

MySQL:获取随机唯一整数ID

python - np.random.rand() 或 random.random()

ios - Swift:从动态 SegmentedControl 获取值

swift - Swift 协议(protocol)扩展中变量的无效重新声明