arrays - 在 Swift 3 中从字典中的数组中检索随机项

标签 arrays swift dictionary arc4random

我几个月来一直在尝试解决这个问题,终于到了我觉得我需要寻求帮助的地步。

最终,我尝试随机化从字典返回的键,然后随机化从其值返回的值。

我的字典是:

var kbDirectory: [String: [String]] = ["Squat": ["4 x 10", "3 x 15", "3 x 20"],
                                   "Deadlift": ["4 x 10", "3 x 15", "3 x 20"],
                                   "2 Handed Swing":["4 x 10", "3 x 15", "3 x 20"],
                                   "Press Up":["4 x 10", "3 x 15", "3 x 20"],
                                   "Pull up":["4 x 10", "3 x 15", "3 x 20"]]

我已经尝试过多次,并尝试从各种来源学习,但似乎无法做到正确。任何答案或指出搜索/学习内容的正确方向将不胜感激。

干杯!

最佳答案

let randomIndex = Int(arc4random_uniform(UInt32(kbDirectory.count)))
let dictValues = Array(kbDirectory.values)
let randomArray = dictValues[randomIndex]
let randomArrayIndex = Int(arc4random_uniform(UInt32(randomArray.count)))
let randomValue = randomArray[randomArrayIndex]

关于arrays - 在 Swift 3 中从字典中的数组中检索随机项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46191503/

相关文章:

c# - Swift:这个 nil 是如何进入我的 [String: AnyObject] 字典的,我该如何摆脱它?

xcode - 快速计算字典中字典的数量

ios - Objective C 在循环外分配数组变量

arrays - 使用不带索引的数组名称获取 Bash 中的第一个数组元素,好吗?

ios - NSMutableArray 重置自身

ios - 为什么我没有获得 UIScrollView 的实际 contentSize?

swift - parse.com 排序嵌套查询

ios - 向带有圆角的 View 添加阴影

python - 将字典理解应用于 defaultdict

c# - 将 ByteArray 转换为 String 以在 TextBox c# 中使用