mysql - 尝试在实例的索引中运行随机数,但出现索引超出范围错误

标签 mysql swift struct instance

我创建了一个结构体来连接到 mysql 数据库,然后为其创建了一个实例。当我尝试运行随机数(在数组大小内)时,我得到默认数字 0,但我的数据库 ID 从 1 开始,因此我收到索引超出范围的错误。

import UIKit
struct PickUpLine: Decodable {
    let id: Int
    let setup: String
}

class PickUpLines: UIViewController {

    private var pul = [PickUpLine ] ()

    @IBOutlet var PULViewController: UIView!

    @IBOutlet weak var PULabel: UITextView!
    override func viewDidLoad() {
        super.viewDidLoad()


        downloadJson()

    }



    @IBAction func generateRandPUL(_ sender: Any) {

        showRandPUL ()

    }

    func showRandPUL (){

        let randomPUL = Int (arc4random_uniform(UInt32(pul.count)))
        PULabel.text = pul[randomPUL].setup // index out of range

    }

    func downloadJson () {
    let url = "https://icebreakerappinc.herokuapp.com/pickuplines"

    print(url)

    //creating let for the url to bond with the link above #2
    guard let url2  = URL (string: url) else {return}
    URLSession.shared.dataTask(with: url2) { (data,response,err) in
        guard let data = data else {return}

        do {
            let PULurl = try JSONDecoder().decode([PickUpLine].self, from: data)

            DispatchQueue.main.async {
                self.PULViewController.reloadInputViews()
                self.pul = PULurl
            }
        }catch let jsonErr {
            print("Error serializing json:" , jsonErr)
        }
        }.resume()

    }
}

最佳答案

只需在 pul array 上使用 randomElement 即可,

let randomPUL = pul.randomElement()
puLabel.text = randomPUL?.setup

Call randomElement() to select a random element from an array or another collection.

Returns

A random element from the collection. If the collection is empty, the method returns nil.

注意:使用驼峰式命名法来命名变量。它应该是 puLabel 而不是 PULabel

更新:

这是 PickUpLines Controller 的外观,

class PickUpLines: UIViewController {
    private var pul = [PickUpLine ] ()

    func showRandPUL (){
        let randomPUL = pul.randomElement()
        puLabel.text = randomPUL?.setup
    }
    //rest of the code...
}

关于mysql - 尝试在实例的索引中运行随机数,但出现索引超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57306161/

相关文章:

c++ - 使用引用成员初始化结构的不同方法

python - 如何在给定范围内在python中生成UUID

ios - 解析查询一开始无法正常工作 iOS Swift

ios - 在 iOS8 Swift 中左对齐 AlertView 消息

ios - 创建一个圆形的 TableViewCell 指示器,就像 Apple Mail 应用程序一样

c - clock_t、time_t 和 struct tm 有什么区别?

php - 将不同的代码从 MySQL 转换为 MySQLi

MySQL 平均每 24 小时 1 个月

php - 按月和年的数据库结果

c - 这个段错误是什么意思