使用函数中的两个值

时间:2018-11-24 16:22:49

标签: swift function

我已经开始使用Swift制作基本的问答游戏。我已经编写了一个结构来定义与每个问题相关的内容:

struct Question {
  let question: String
  let answers: [String]
  let correctAnswer: Int
}

该游戏将是基本的数学测验,因此将显示随机的数学问题。我编写了一个函数来随机化问题并获得答案:

func questionAnswerBuilder() -> (question: String, answer: String) {
let first: Int = randomNumber()
let second: Int = randomNumber()
let arr = [first,second].sorted(by: >)

let firstAsString = String(arr[0])
let secondAsString = String(arr[1])

let questionString = "\(firstAsString) + \(secondAsString)"
let question = questionString

//Answer:
let answerString = first + second
let answer = String(answerString)

return (question, answer)
}

我已经在操场上对此进行了测试,并且效果很好。每次它创建一个随机数并将其与正确答案一起输出。现在,我想在每个问题中使用它...

var questionTest = questionAnswerBuilder()

var questions: [Question] = [
Question(question: questionTest.question, answers: [randomAnswer(), randomAnswer(), questionAnswerBuilder().answer, randomAnswer()], correctAnswer: 2),
Question(question: questionTest.question, answers: [randomAnswer(), randomAnswer(), questionAnswerBuilder().answer, randomAnswer()], correctAnswer: 2)
]

有关信息,此处不显示randomAnswer()功能。基本上,它只是一个随机数生成器。

当我将所有这些都输入Xcode时,我得到以下消息: Cannot use instance member 'questionTest' within property initializer; property initializers run before 'self' is available

我目前在自己的快捷文件中拥有questionAnswerBuilder()函数。我尝试将其移至与我的questions变量相同的文件中,但是仍然遇到相同的错误。我也尝试过使questionTest变量变懒,但这没什么区别。

请请有人指出我要去哪里错了!

谢谢!

2 个答案:

答案 0 :(得分:0)

哦,您不能在其他实例变量中使用实例变量。

您可以通过将questions数组更改为lazy var questions来解决此问题。

这不会在实例化点时创建数组。只会在您首次访问该数组时创建该数组。

答案 1 :(得分:0)

您不能初始化在类的顶层相互依赖的属性。

一种解决方案是延迟questions初始化

lazy var questions: [Question] = {
    return [Question(question: questionTest.question, answers: [randomAnswer(), randomAnswer(), questionAnswerBuilder().answer, randomAnswer()], correctAnswer: 2),
            Question(question: questionTest.question, answers: [randomAnswer(), randomAnswer(), questionAnswerBuilder().answer, randomAnswer()], correctAnswer: 2)]
}()