我仍在努力快速地思考可选值。有人可以解释为什么当我们创建模型对象时我们放了一个 '!'在创建 quizCountries 字符串数组之后以及创建字符串数组时,我们还放置了 '!'并将其设置为零。我真的不明白为什么我们希望程序中的某些东西永远为零。
// QuizViewController.swift
import UIKit
class QuizViewController: UIViewController, ModelDelegate {
@IBOutlet weak var flagImageView: UIImageView!
@IBOutlet weak var questionNumberLabel: UILabel!
@IBOutlet weak var answerLabel: UILabel!
@IBOutlet var segmentedControls: [UISegmentedControl]!
private var model: Model! // reference to the model object
private let correctColor = UIColor(red: 0.0, green: 0.75, blue: 0.0, alpha: 1.0)
private let incorrectColor = UIColor.redColor()
private var quizCountries: [String]! = nil // countries in quiz
private var enabledCountries: [String]! = nil // countries for guesses
private var correctAnswer: String! = nil
private var correctGuesses = 0
private var totalGuesses = 0
最佳答案
属性名称后的感叹号表示这是一个隐式展开的可选。
Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter. The primary use of implicitly unwrapped optionals in Swift is during class initialization, as described in Unowned References and Implicitly Unwrapped Optional Properties.
这些在引用对象时很有用,例如model
在您的情况下,在 QuizViewController
初始化时尚不清楚,但仍保证可用并分配给 model
属性在首次使用之前。 quizCountries
也是如此,我们在创建 Controller 时还不知道这些国家,但在使用它们之前肯定会知道它们。
如果隐式解包可选,与预期相反,在使用时(仍然)nil
应用程序将崩溃。
关于swift - 在 swift 中解包选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28655719/