ios - 快速返回随机字典项

标签 ios ios7 swift io tuples

到目前为止,我正在尝试从该函数返回一个随机名称和一封随机电子邮件,但我想知道我应该在这里返回什么,因为我想返回一个元组,它需要是 2 个字符串值我需要从我的函数中随机获取

func randomAuthor () -> (name : String, email : String) {

    struct Author {

        var name : String
        var email : String

    }

    let firstAuthor = Author(name: "jon", email: "jonsEmail")
    let secondAuthor = Author(name: "richard", email: "richardsEmail")
    let thirdAuthor = Author(name: "steve", email: "stevesEmail")
    let fourthAuthor = Author(name: "simon", email: "simonsEmail")
    let fifthAtouh = Author(name: "wes", email: "wesEmail")

    var dictionary = [firstAuthor.name : firstAuthor.email, secondAuthor.name : secondAuthor.email, thirdAuthor.name : thirdAuthor.email, fourthAuthor.name : fourthAuthor.email, fifthAuthor.name : fithAtouh.email]

    var unsignedDictionaryCount = UInt32(dictionary.count)
    var unsignedRandom = arc4random_uniform(unsignedDictionaryCount)
    var random = unsignedRandom


    return()

}

感谢任何帮助 谢谢

最佳答案

分几步从字典中随机取值:

  1. 创建你的词典
  2. 使用arc4random_uniform获取随机Int
  3. 使用这个随机的Int得到一个随机的key(using keys),并得到它的值
  4. 返回它们,您就完成了!

    var dictionary : [String:String] =  [firstAuthor.name : firstAuthor.email, secondAuthor.name : secondAuthor.email, thirdAuthor.name : thirdAuthor.email, fourthAuthor.name : fourthAuthor.email]
    let index: Int = Int(arc4random_uniform(UInt32(dictionary.count)))
    let value = Array(dictionary.values)[index]
    let key = Array(dictionary.keys)[index]
    let value = dictionary[key]
    return (key, value!)
    

关于ios - 快速返回随机字典项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26852226/

相关文章:

ios - 如何为 inputAccessoryView 设置动画

ios - 取消呈现的 View Controller 的交互式关闭转换后, View Controller 不会自动旋转

javascript - Mobile safari 崩溃日志 - 内存不足

ios - NSDate 的解析时间

ios - 发现信标的最佳测距方式?

ios - 支持 iOS 6 和 7

ios - 如何防止修改字典副本

ios - 如何在 UIView(不是 UITableView、UICollectionView、UIScrollView)上添加拉动刷新

ios - 应用内购买 - 购买成功但交易失败

ios - 更新 UILabel 文本动画