gpt4 book ai didi

swift - 在 swift 中解包选项

转载 作者:搜寻专家 更新时间:2023-11-01 06:23:37 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com