gpt4 book ai didi

ios - Xcode 8 中隐式解包的可选分配

转载 作者:行者123 更新时间:2023-11-30 12:31:07 25 4
gpt4 key购买 nike

在Xcode 8发布版本中,我发现了一个奇怪的场景。

这是代码,

let implicitlyUnwrappedOptionalString: String! = "implicitlyUnwrappedOptionalString"
let foo = implicitlyUnwrappedOptionalString

print(implicitlyUnwrappedOptionalString)
print(foo)

这是结果:

implicitlyUnwrappedOptionalString
Optional("implicitlyUnwrappedOptionalString")

上面的内容表明,当我将隐式展开的可选分配给没有显式类型的变量时,该类型将被推断为可选类型,而不是它最初的类型,即>隐式解包可选

我的 Xcode 已更新到 8。任何人都可以验证 Xcode 7.x 中的行为吗?

该变化是由于 Swift 版本更改还是 Xcode 导致的?

最佳答案

这是 SE-0054 Abolish ImplicitlyUnwrappedOptional type 的结果已在 Swift 3 中实现。该提案摘录(已添加重点):

However, the appearance of ! at the end of a property or variable declaration's type no longer indicates that the declaration has IUO type; rather, it indicates that (1) the declaration has optional type, and (2) the declaration has an attribute indicating that its value may be implicitly forced. ...

If the expression can be explicitly type checked with a strong optional type, it will be. However, the type checker will fall back to forcing the optional if necessary. The effect of this behavior is that the result of any expression that refers to a value declared as T! will either have type T or type T?. For example, in the following code:

let x: Int! = 5
let y = x
let z = x + 0

… x is declared as an IUO, but because the initializer for y type checks correctly as an optional, y will be bound as type Int?. However, the initializer for z does not type check with x declared as an optional (there's no overload of + that takes an optional), so the compiler forces the optional and type checks the initializer as Int.

就您而言,作业

let foo = implicitlyUnwrappedOptionalString

使 foo 成为强可选,如示例 let y = x来自提案。

可以通过添加显式类型注释来使 foo 成为 IUO

let foo: String! = implicitlyUnwrappedOptionalString

但通常你应该尝试摆脱代码中的 IUO,正如同一提案中所述:

Except for a few specific scenarios, optionals are always the safer bet, and we’d like to encourage people to use them instead of IUOs.

关于ios - Xcode 8 中隐式解包的可选分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43550315/

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