初始分配后可变变不变
有没有一种方法可以使变量在初始化/分配后变得不可变,以便它可以在某个时刻发生变化,但稍后又变得不可变?我知道我可以创建一个新的 let
变量,但是有没有办法在不创建新变量的情况下做到这一点?
如果不是,那么安全地确保变量在需要时不被更改的最佳实践是什么? 我想要完成的示例:
var x = 0 //VARIABLE DECLARATION
x += 1 //VARIABLE IS CHANGED AT SOME POINT
x = let x //MAKE VARIABLE IMMUTABLE AFTER SOME FUNCTION IS PERFORMED
x += 5 //what I'm going for: ERROR - CANNOT ASSIGN TO IMMUTABLE VARIABLE
Is there a way to make a variable immutable after initializing/assigning it, so that it can change at one point, but later become immutable? I know that I could create a new let
variable, but is there a way to do so without creating a new variable?
If not, what is best practice to safely ensure a variable isn't changed after it needs to be?
Example of what I'm trying to accomplish:
var x = 0 //VARIABLE DECLARATION
x += 1 //VARIABLE IS CHANGED AT SOME POINT
x = let x //MAKE VARIABLE IMMUTABLE AFTER SOME FUNCTION IS PERFORMED
x += 5 //what I'm going for: ERROR - CANNOT ASSIGN TO IMMUTABLE VARIABLE
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用内联闭包初始化变量:
You can initialize a variable with an inline closure:
我不知道这使您可以将
var
变量更改为LET
以后常数。但是您可以将您的常数声明为让
开始,而不是立即给它一个值。只要您在使用它之前的某个时候为常数分配一个值,就可以,因为编译器可以确定最终将被填充。例如
如果其他
有效,则由于有条件的分支之一可以被调用。There's no way I know of that lets you change a
var
variable into alet
constant later on. But you could declare your constant aslet
to begin with and not immediately give it a value.As long as you assign a value to your constant sometime before you use it, you're fine, since the compiler can figure out that it will eventually be populated. For example
if else
works, since one of the conditional branches is guaranteed to get called.