【问题标题】:Retrieving a random item out of an array within a dictionary in Swift 3从 Swift 3 中的字典中的数组中检索随机项
【发布时间】:2017-09-13 15:43:56
【问题描述】:

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

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

我的字典是:

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"]]

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

干杯!

【问题讨论】:

  • 不要犹豫,展示您的尝试,以便我们了解您的问题所在并提供相应的帮助!

标签: arrays swift dictionary arc4random


【解决方案1】:
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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-22
    • 2017-03-27
    • 2017-06-23
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 2018-01-05
    • 2021-12-12
    相关资源
    最近更新 更多