gpt4 book ai didi

swift - 在 Swift 中使用具有相同变量名的可选绑定(bind)

转载 作者:可可西里 更新时间:2023-11-01 00:57:08 25 4
gpt4 key购买 nike

我正在学习 Swift。我在一本书中看到了这些代码行。

import UIKit

var errorCodeString : String?
errorCodeString = "404"
var errorDescription : String?

if let theError = errorCodeString,
let errorCodeInteger = Int(theError),
errorCodeInteger == 404 {

errorDescription = "\(errorCodeInteger + 200) : resource was not found."
}

var upCaseErrorDescription = errorDescription?.uppercased()
errorDescription

upCaseErrorDescription?.append("PLEASE TRY AGAIN")
upCaseErrorDescription

errorDescription = nil
let description: String
if let errorDescription = errorDescription {
description = errorDescription
} else {
description = "NO ERROR"
}

对于这一行:

if let errorDescription = errorDescription

errorDescription 从一开始就声明为变量,并再次声明为常量。
我在这里有点困惑。这两个“errorDescription”是否相同?

最佳答案

I am a bit confused here. Are these two "errorDescription" the same?

实际上,它们并不完全相同。

对于这种情况,访问 if let block 内的 errorDescription 将被引用到一个新的 -unwrapped- 常量(没有 ?)

if let errorDescription = errorDescription {
print(errorDescription)
}

证明它!

无论如何在您的真实应用中您都不需要这样做,这只是为了让您清楚。

如果你试图更新解包变量的值,它不会影响到原来的 -optional- 一个,例如:

var myString: String? = "Hello"

if var myString = myString {
myString += " World"
}

print(myString) // Optional("Hello")

如您所见,myString 值仍然相同(不是“Hello World”)。

证明它们不相同的另一种方法:如果您在类/结构中声明它,您可以让编译器通过使用 self 来识别您的实例变量和展开的常量:

struct MyStruct {
var myString: String? = "Hello"

func sayHello() {
if var myString = myString {
myString += " World" // here is the unwrapped constant ("Hello World")
print(self.myString) // here is the instance variable ("Optional("Hello")\n")
}
}
}

关于swift - 在 Swift 中使用具有相同变量名的可选绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44131582/

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