简体   繁体   English

为什么在Swift中包装可选值? 是否可以在不声明类型的情况下将变量设置为可选变量?

[英]Why Wrapped Optional Values in Swift? Is it possible to set a variable as optional without declaring a type?

If I want to make a variable an optional, I can do: 如果我想将变量设为可选,则可以执行以下操作:

var exampleString: String? = nil

or 要么

var exampleString: String? = "This is a string"

Is it possible to declare an optional value without assigning a type like String, Int, Bool, etc? 是否可以在不分配String,Int,Bool等类型的情况下声明可选值?

Something like (that doesn't return an error): 一样的东西(不会返回错误):

var exampleVar? = nil

I have no use case for why I want to do this, but I'm trying to better understand optionals. 对于为什么要这样做,我没有用例,但是我试图更好地理解可选。 I just read through the Optionals section in Swift docs. 我只是通读了Swift文档中的Optionals部分。 If this can be done, would there be any advantage to doing this? 如果能够做到这一点,这样做会有什么好处吗?

Also, why would I not want to use implicitly unwrapped optionals everywhere? 另外,为什么我不想在所有地方都使用隐式解包的可选内容? What would be the disadvantages of this? 这有什么缺点? Apple's Swift docs mentions that you shouldn't do this if you intend to reassign a variable to nil. Apple的Swift文档提到,如果您打算将变量重新分配为nil,则不应这样做。 Why? 为什么?

Thanks so much for your help guys! 非常感谢您的帮助!

Is it possible to declare an optional value without assigning a type like String, Int, Bool, etc? 是否可以在不分配String,Int,Bool等类型的情况下声明可选值?

No. The reason is that Optional (without its generic parameter) is not a complete type — think of it as a type constructor , ie a way to produce a full type if you give it the missing information. 否。原因是Optional (没有其通用参数)不是完整的类型-将其视为类型构造函数 ,即,如果您给它提供缺少的信息,则可以生成完整的类型。

The compiler needs to know the full type — Optional<Int> or Optional<String> and so on — to allocate the right amount of memory etc. An Optional<String> will take up more memory than an Optional<Bool> , even if both are nil . 编译器需要知道完整类型Optional<Int>Optional<String> ,依此类推-分配合适的内存量等。即使Optional<String>也会比Optional<Bool>占用更多的内存。两者均nil

The same is true for other generic types like Array . 对于其他通用类型(如Array也是如此。 Array is the type constructor, Array<Int> the complete type. Array是类型构造函数, Array<Int>是完整类型。

Edit: rmaddy makes a good point: var exampleVar: Any? = nil 编辑: rmaddy提出了一个要点: var exampleVar: Any? = nil var exampleVar: Any? = nil allows you to store any value in this optional. var exampleVar: Any? = nil允许您在此可选参数中存储任何值。 Note that we're still dealing with a full type here — Optional<Any> . 请注意,我们仍然在这里处理完整类型Optional<Any> It's just that all types are compatible with Any . 只是所有类型都与Any兼容。 In that sense, Optional<Any> is not much different from Optional<SomeProtocol> , which can store any value that conforms to the SomeProtocol protocol. 从这个意义上讲, Optional<Any>Optional<SomeProtocol> Optional<Any>并没有太大区别,后者可以存储符合SomeProtocol协议的任何值。

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

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