使用地图隐式展开可选的奇怪行为

Implicitly unwrapped optional strange behaviour with map

我发现了什么

这个问题是关于我在 Swift 语言中注意到的一些奇怪的事情。我遇到了这种行为,因为它是我代码中的错误。

如果我为网格创建一个数组作为隐式展开的可选,那么 map 会表现得很奇怪。看看这段代码:

let grid: [[Int]]! = [ // May be defined like this if set later on
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]


print(grid.map { [=10=][0] }!)
// Prints "[1, 2, 3]" (not what I wanted)

print(grid!.map { [=10=][0] })
// Prints "[1, 4, 7]" (what I wanted)

我知道可以通过 grid[0] 简单地获得该行。但是,我正在尝试获取专栏。

我试过上面的第一种方法,只给出行而不是列。第二种方法奏效,给了专栏。

这是什么原因?

我将 grid 定义为 [[Int]]!,这是一个隐式展开的可选值。

map有两个版本:一个对数组进行操作,另一个对optionals.

进行操作

你的 grid 是一个 可选的 ,即使它是一个 隐式展开的可选 (IUO) 它仍然是可选。 Swift 将尽可能将 IUO 视为 可选 并且仅在需要解包类型时才强制解包值。

因此,可选 版本的 map 被使用,而不是您期望的版本。通过用 ! 显式解包 grid,然后允许使用所需版本的 map

map 如何在 可选 上工作?

当 map 应用于 optional 时,它会将闭包应用于展开的值。如果 可选 nil,什么也不会发生。

因此,grid 展开并变为 [=19=],而闭包 returns [=20=][0]grid 的第一行。


注意: 在 Xcode 中,如果您 选项 - 单击每个语句中的 map 您将看到第一个说:

Evaluates the given closure when this Optional instance is not nil, passing the unwrapped value as a parameter.

第二个:

Returns an array containing the results of mapping the given closure over the sequence’s elements.