英文:
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 to1
"two"
is ignorednil
is nil-coalesced to"0"
and mapped to0
With the bad/wrong type annotation [Int?]
the following happens
"1"
is mapped toOptional(1)
"two"
cannot be converted toInt
so instead of ignoring the valuenil
is returnednil
is nil-coalesced to"0"
and mapped toOptional(0)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论