gpt4 book ai didi

ios - 如何在函数外声明具有结构数组的变量

转载 作者:行者123 更新时间:2023-11-28 06:13:55 27 4
gpt4 key购买 nike

我需要在 randomQuestionGenerator 函数之外使用 currentQuestion 变量。预先声明它的正确语法是什么?

struct Questions {
var Question: String
var answer: Int
var answers: [String]
}

class GameScreen: UIViewController {

var correctAnswer = 0
var fullQuestions: [Questions] = []

func RandomQuestionGenerator(){
let randomQuestion =
Int(arc4random_uniform(UInt32(fullQuestions.count)))
var currentQuestion = fullQuestions[randomQuestion]
correctAnswer = currentQuestion.answer

最佳答案

您可以将 currentQuestion 声明为函数外的可选:

var currentQuestion : Questions? = nil
func RandomQuestionGenerator() {
let randomQuestion = Int(arc4random_uniform(UInt32(fullQuestions.count)))
currentQuestion = fullQuestions[randomQuestion]
correctAnswer = currentQuestion.answer
}

尽管您可以这样做,但更好的方法是让您的函数返回随机问题,如下所示:

func RandomQuestionGenerator() -> Questions {
let randomQuestion = Int(arc4random_uniform(UInt32(fullQuestions.count)))
return fullQuestions[randomQuestion]
}

现在您可以使用该函数检索下一个随机问题,并根据需要获取其字段:

let nextQuestion = RandomQuestionGenerator()
print(nextQuestion.Question)
print(nextQuestion.answers)

关于ios - 如何在函数外声明具有结构数组的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45685438/

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