gpt4 book ai didi

ios - 在 Xcode 8 中隐式展开可选分配

转载 作者:搜寻专家 更新时间:2023-10-31 08:15:14 25 4
gpt4 key购买 nike

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

这是代码,

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/39633481/

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