简体   繁体   English

将非可选变量更改为Swift可选类型会破坏其在代码中的所有出现

[英]Changing non-optional variable to Swift optional type breaks all its occurrences in code

I have an instance variable that's not declared as an optional type in Swift (it always has an initial value). 我有一个实例变量在Swift中没有声明为可选类型(它始终具有初始值)。

var array: Array<MyObject> = []

Later in my project I realized I should make it an optional: 后来在我的项目中,我意识到我应该使其成为可选项:

var array: Array<MyObject>?

When I do this, however, it breaks all occurrences of the variable in the current code. 但是,当我这样做时,它将中断当前代码中所有出现的变量。 I suddenly have to append a ? 我突然不得不追加一个? to every time it is invoked. 到每次被调用时。

Is there a way of writing variables in Swift such that its occurrences do not break when you toggle between making it optional and non-optional? 有没有一种方法可以在Swift中编写变量,从而在将其设置为可选和非可选之间切换时,它的出现不会中断?

If you don't want to make it a real optional, but it needs to be nil , you can make it an implicitly unwrapped optional . 如果您不想将其设为真正的可选,但需要为nil ,则可以将其设为隐式展开的可选 You declare one like this: 您可以这样声明:

var foo: String!

Then you can just use it like you do now, but it can be nil as well. 然后,您可以像现在一样使用它,但是也可以nil You should only use it without a nil-check if you're really sure you did actually set it. 如果您确实确定确实设置了它,则应仅使用nil-check。

But this is not the good way, since you lose the safety which Swift provides for optionals. 但这不是一个好方法,因为您失去了Swift提供的可选选项的安全性。 I can still only recommend refactoring to an optional, but if that's not possible this should do the trick. 我仍然只能建议将重构重构为可选的,但是如果不可能的话,这应该可以解决问题。

For more info about implicitly unwrapped optionals, I would like to refer to the chapters "The Basics" and "Automatic Reference Counting" in "The Swift Programming Language" iBook by Apple. 有关隐式展开的可选内容的更多信息,我想参考 Apple iBook中的“ The Swift Programming Language”中的 基础”“自动引用计数”两章。

Not really, no. 不是,不是
(You might be able to get away with some refactoring features of Xcode, like Rename All in Scope.) (您也许可以摆脱Xcode的一些重构功能,例如在Scope中重命名所有。)

But this is actually a good thing! 但这实际上是一件好事! If you realize that a variable needs to be optional, well, the rest of your code must realize it too , and handle it appropriately. 如果您意识到变量必须是可选的, 那么其余的代码也必须实现它 ,并适当地处理它。 In Swift, this is enforced. 在Swift中,这是强制执行的。

Enjoy writing safer code! 享受编写更安全的代码!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM