swift - 在 swift 中解包选项

标签 swift option-type

我仍在努力快速地思考可选值。有人可以解释为什么当我们创建模型对象时我们放了一个 '!'在创建 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/

相关文章:

ios - 音调在 Audikit 4.2 中不播放,但在 4.1 版本中工作正常

ios - 将 Swift 代码导入 Objective-C 文件

ios - 代码签名错误 : bundle format unrecognized, 无效,或不合适

ios - swift 3 : CAShapeLayer mask not animating for pie chart animation

java - 有没有办法使用 'orElseGet'的方法 'Optional'在它为空时创建一个新列表?

java - Optional.ofNullable() 中的空指针异常

java - 不使用 isPresent 重写Optional

generics - 如何确定泛型在 Swift 中是否是可选的?

haskell - 编写此代码的更短方法

Swift、OpenGL 和 glVertexAttribPointer