首页 > 解决方案 > 可选类型“问题?”的值 必须解包以引用已包装基本类型“问题”的成员“问题文本”

问题描述

我正在制作一个小问答ios应用程序。我希望第一个问题是随机的。我的代码如下。

let allQuestions = QuestionBank()
var pickedAnswer : Bool = false
//Place your instance variables here


@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet var progressBar: UIView!
@IBOutlet weak var progressLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    let firstQuestion = allQuestions.list.randomElement();
    questionLabel.text = firstQuestion.questionText

}

我正在使用 .list 访问数组,但我希望每次启动应用程序时第一个问题都是随机元素。任何帮助,将不胜感激。

标签: iosarraysswift

解决方案


它看起来像firstQuestioncan be nil,所以它是 type Question?。如果你想使用它的questionText属性,你必须解开你的问题。一种方法是通过可选绑定

if let firstQuestion = allQuestions.list.randomElement() {
    questionLabel.text = firstQuestion.questionText
}

推荐阅读