ios - 可选类型“问题?”的值 必须解包以引用已包装基本类型“问题”的成员“问题文本”
问题描述
我正在制作一个小问答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 访问数组,但我希望每次启动应用程序时第一个问题都是随机元素。任何帮助,将不胜感激。
解决方案
它看起来像firstQuestion
can be nil
,所以它是 type Question?
。如果你想使用它的questionText
属性,你必须解开你的问题。一种方法是通过可选绑定
if let firstQuestion = allQuestions.list.randomElement() {
questionLabel.text = firstQuestion.questionText
}
推荐阅读
- huawei-mobile-services - 由于 Skybox 制作程序未与开发文档中的示例代码一起发布,因此无法集成 HMS 计算机图形套件示例代码
- zillow - Zillow API 返回 410 响应
- java - 在Java中,变量或参数可以设置子类的父类吗?
- asp.net - "ErrorMessage":"找不到 ABCGeckoWP.exe。"
- php - 随机替换字符串中的单词
- c++ - 在什么情况下 C++11 = 默认构造函数与不带参数和空主体的构造函数不同?
- roblox - workspace.Tool.Handle.Script6:无效参数#3(需要 Vector3,得到实例)
- android - Android 的 CameraX/Camera2 可以同时处理 2 个预览或/和 2 个记录吗?
- c# - 如何从 Microsoft.Extensions.Configuration.IConfiguration 读取动态对象
- asp.net-mvc - 你如何在 asp.net core mvc 中设置动态路由