默认情况下,未分配的常量不会为 nil

2023-09-08移动开发问题
3

本文介绍了默认情况下,未分配的常量不会为 nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我目前的理解:如果你定义一个可选变量而不赋值,编译器会自动赋值nil

My understanding so far : If you define an optional variable without assign any values, the compiler will automatically assign the nil

代码片段:

A:

var someOptional : Int? //Change to `let` to trigger error 
var aDefaultValue = 42
var theAnswer = someOptional ?? aDefaultValue

上面的代码片段可以正常工作,但是,当我将变量 someOptional 更改为常量时,编译器会报错(请参见下图)

The code snippet above works fine, however, when I changed the variable someOptional to a constant, the compiler yelled an error (Please see the attached figure below)

乙:

然后我尝试了类似的代码来解决问题.

I then tried the similar codes to down to the problem.

var someOptional : Int?
print(someOptional)

不过,它对变量工作正常,而对常量类型失败.

Still, it works fine with variable while failed with the constant type.

结论:

如果你定义了一个可选的常量,你必须明确地指定 nil.因为它看起来没用(为什么你需要一个用 nil 赋值的常量选项),如果编译器自动为你这样做,它可能会引入错误.

If you define a constant optional you have to assign the nil explicitly if you mean that. Because it looks useless (why do you need a constant option with assigned with nil), if the compiler did that for you automatically it may introduce an error.

问题:

为什么编译器假定 nilvar 声明的可选值而不是 let 声明的可选值?

Why does the compiler assume nil for var declared optionals but not for let declared optionals?

推荐答案

是的,没错

可选变量不需要手动初始化.如果您在填充之前阅读它确实包含 nil.

来自 Apple 文档

如果您定义一个可选变量而不提供默认值,则该变量会自动为您设置为 nil [...]

If you define an optional variable without providing a default value, the variable is automatically set to nil for you [...]

另一方面,编译器会强制您在读取可选常量 (let) 之前手动初始化它.

On the other hand the compiler does force you to manually initialize an Optional constant (let) before you can read it.

与变量不同,常量的值一旦设置就不能更改.尝试这样做会在编译代码时报告为错误 [...]

Unlike a variable, the value of a constant cannot be changed once it is set. Attempting to do so is reported as an error when your code is compiled [...]

为什么?

一个常数只能写一次.它不需要发生在它被初始化的同一行,但它必须在你阅读它之前发生.

Why?

A constant can be written only once. It doesn't need to happened on the same line it is initialized but it must happened before your read it.

例如这段代码运行良好

let num: Int?
num = 1
print(num)

但是,如果编译器在 num 中放置了一个临时 nil 值,那么该常量将被写入两次.这违反了常数的概念.

However if the compiler had put a temporary nil value inside num then the constant would have been wrote twice. Which is against the concept of constant.

let num: Int?
print(num) // nil ??? <- this can't work! 
num = 1
print(num) // 1

另一个例子

此代码段运行良好

Another example

This code snippet works fine

func printArea(width: Int?, height:Int?) {
    let area: Int?
    if let width = width, height = height {
        area = width * height
    } else {
        area = nil
    }
    print(area)
}

同样,如果编译器在 area 中放置了一个临时 nil 值,那么...

Again, if the compiler had put a temporary nil value inside area then...

func printArea(width: Int?, height:Int?) {
    let area: Int?
    print(area) // not possible! area is going to change in a moment
     if let width = width, height = height {
        area = width * height
    } else {
        area = nil
    }
    print(area)
}

这篇关于默认情况下,未分配的常量不会为 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法将文件从捆绑包复制到 iOS 中的文档目录
Can`t copy file from bundle to documents directory in iOS(无法将文件从捆绑包复制到 iOS 中的文档目录)...
2024-04-15 移动开发问题
4

如何复制“字典"在斯威夫特?
How to copy a quot;Dictionaryquot; in Swift?(如何复制“字典在斯威夫特?)...
2024-04-15 移动开发问题
10

Swift - 迭代结构对象时如何对其进行变异
Swift - How to mutate a struct object when iterating over it(Swift - 迭代结构对象时如何对其进行变异)...
2024-04-15 移动开发问题
7

如何使用 Swift 将文本复制到剪贴板/粘贴板
How to copy text to clipboard/pasteboard with Swift(如何使用 Swift 将文本复制到剪贴板/粘贴板)...
2024-04-15 移动开发问题
9

Swift 无法使用类型为“([Score],Score)"的参数列表调用“find",其中 Sco
Swift Cannot invoke #39;find#39; with an argument list of type #39;([Score], Score)#39; where Score is a struct(Swift 无法使用类型为“([Score],Score)的参数列表调用“find,其中 Score 是一个结构)...
2024-04-15 移动开发问题
6

如何使用 UIImageViewExtension 与 Swift 异步加载图像并防止重复图像或错误图像加载到单元格
How to load image asynchronously with Swift using UIImageViewExtension and preventing duplicate images or wrong Images loaded to cells(如何使用 UIImageViewExtension 与 Swift 异步加载图像并防止重复图像或错误图像加载到单元格) - IT屋-程序员软...
2024-04-15 移动开发问题
3