gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:43:42 28 4
gpt4 key购买 nike

我创建了一个结构体来连接到 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com