如何在Swift中访问字典中的随机元素 [英] How to access a random element in a dictionary in Swift

查看:187
本文介绍了如何在Swift中访问字典中的随机元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了以下代码:

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,但是找不到关于它的任何文档.

How can I select a random element from the dictionary? I think I should use arc4random_uniform but couldn't find any documentation on it.

推荐答案

您必须解决一些问题,但这似乎可行.

You have to cast some things around, but this seems to work.

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

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

Basically, generate a random index value between zero and the total item count. Get the values of the dictionary as an array and then fetch the random index.

您甚至可以将其包装在扩展名中,以方便访问.

You could even wrap that in an extension for easy access.

这篇关于如何在Swift中访问字典中的随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆