Swift compactMap 包括 nil 值

huangapple go评论63阅读模式
英文:

Swift compactMap includes nil value

问题

The result printed is [Optional(1), nil, Optional(0)], why does it include the nil value? I thought these would be filtered out because of compactMap.

Interestingly let intArray: [Int] = numbers.compactMap {Int($0 ?? "0")} works without an issue.

英文:

Consider the following:

let numbers: [String?] = ["1", "two", nil]
let intArray: [Int?] = numbers.compactMap {Int($0 ?? "0")}
print(intArray)

The result printed is [Optional(1), nil, Optional(0)], why does it include the nil value? I thought these would be filtered out because of compactMap.

Interestingly let intArray: [Int] = numbers.compactMap {Int($0 ?? "0")} works without an issue.

答案1

得分: 4

这是一个很好的例子,说明显式类型注释有时会让事情变得更糟。

根据定义,compactMap 返回一个非可选数组。

没有类型注释:

let intArray = numbers.compactMap {Int($0 ?? "0")}

或者使用正确的类型注释:

let intArray: [Int] = numbers.compactMap {Int($0 ?? "0")}

结果是:

[1, 0]
  • “1” 被映射为 1
  • “two” 被忽略
  • nil 被nil-合并为 “0” 并映射为 0

使用不正确的类型注释 [Int?] 会发生以下情况:

  • “1” 被映射为 Optional(1)
  • “two” 无法转换为 Int,所以不是忽略该值,而是返回 nil
  • nil 被nil-合并为 “0” 并映射为 Optional(0)
英文:

This is a good example why explicit type annotation makes things sometimes worse.

According to the definition compactMap returns a non-optional array.

Without type annotation

let intArray = numbers.compactMap {Int($0 ?? "0")}

or with the correct type annotation

let intArray : [Int] = numbers.compactMap {Int($0 ?? "0")}

the result is

[1, 0]
  • "1" is mapped to 1
  • "two" is ignored
  • nil is nil-coalesced to "0" and mapped to 0

With the bad/wrong type annotation [Int?] the following happens

  • "1" is mapped to Optional(1)
  • "two" cannot be converted to Int so instead of ignoring the value nil is returned
  • nil is nil-coalesced to "0" and mapped to Optional(0)

huangapple
  • 本文由 发表于 2023年5月26日 15:49:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76338711.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定