FlatMap使用Int类型数组给出警告,但不使用String类型数组给出警告

问题描述 投票:0回答:1

当我将flatMapString类型的数组一起使用时,它没有给出任何警告,而在Int类型的数组中它给出了警告。为什么?示例:

let strings = [
    "I'm excited about #SwiftUI",
    "#Combine looks cool too",
    "This year's #WWDC was amazing"
]
strings.flatMap{$0 + "."} //No warning

let ints = [
   2,3,4
]
ints.flatMap{$0 + 1} //'flatMap' is deprecated: Please use compactMap(_:) for the case where closure returns an optional value
ios swift flatmap
1个回答
3
投票

因为这是两种不同的flatMap方法。

所以,在我回答您的问题之前,让我们退后一步,考虑一下flatMap现在打算做什么(即,将数组的数组展平):

let arrayOfArrays = [[1, 2], [3, 4, 5]]
let array = arrayOfArrays.flatMap { $0 }
print(array)

结果:

[1、2、3、4、5]

[flatMap已将数组的数组展平为单个数组。

令人困惑的是,还有另一个flatMap会取消包装可选内容,从而删除那些nil。幸运的是,现在已将其重命名为compactMap以避免混淆,这就是收到警告的原因。

考虑:

let input: [Int?] = [0, 1, nil, 3]
let results = input.flatMap { $0 } // 'flatMap' is deprecated: Please use compactMap(_:) for the case where closure returns an optional value
print(results)

结果:

[0,1,3]

但是,我们建议您将flatMap替换为compactMap

let input: [Int?] = [0, 1, nil, 3]
let results = input.compactMap { $0 }
print(results)

将在没有警告的情况下为我们提供预期的结果。


所以,让我们回到您的示例。因为字符串是字符数组,所以它会让您如履薄冰:

let strings = [
    "I'm excited about #SwiftUI",
    "#Combine looks cool too",
    "This year's #WWDC was amazing"
]
let stringResults = strings.flatMap { $0 + "." }
print(stringResults)

其结果是扁平化的字符数组:

[[“ I”,“ \'”,“ m”,“”,“ e”,“ x”,“ c”,“ i”,“ t”,“ e”,“ d”,“”, “ a”,“ b”,“ o”,“ u”,“ t”,“”,“#”,“ S”,“ w”,“ i”,“ f”,“ t”,“ U” ,“ I”,“。”,“#”,“ C”,“ o”,“ m”,“ b”,“ i”,“ n”,“ e”,“”,“ l”,“ o ”,“ o”,“ k”,“ s”,“”,“ c”,“ o”,“ o”,“ l”,“”,“ t”,“ o”,“ o”,“”。 “, “这些年”, ” ”, ” #“,” W“,” W“,” D“,” C“,”“,” w“,” a“,” s“,”“,” a“,” m“,” a“,” z“,” i“,” n“,” g“,”。“]

这显然不是您想要的,但是编译器让您如愿以偿,您想将字符数组(即字符串数组)展平为平坦的字符数组。这就是为什么没有警告的原因。


[不用说,在您的示例中,您既不会使用flatMap(因为您不处理数组数组),也不会使用compactMap(因为您不处理可选内容)。您只需使用map

let strings = [
    "I'm excited about #SwiftUI",
    "#Combine looks cool too",
    "This year's #WWDC was amazing"
]
let stringsResults = strings.map { $0 + "." }
print(stringsResults)

let ints = [2, 3, 4]
let intsResults = ints.map { $0 + 1 }
print(intsResults)
© www.soinside.com 2019 - 2024. All rights reserved.