struct Product {
let name: String
let weight: Double
}
let productsList = [Product(name: "AAA", weight: 1),
Product(name: "BBB", weight: 2),
Product(name: "CCC", weight: 3),
Product(name: "DD", weight: 4),
Product(name: "RR", weight: 5),
Product(name: "EEE", weight: 6),
Product(name: "FGT", weight: 7),
Product(name: "DSF", weight: 8),
Product(name: "VCVX", weight: 9),
Product(name: "GFDHT", weight: 10)]
print(productsList.map { $0.name })
我从上面的行中获取所有产品名称,但我想仅使用map从奇数索引中获取名称。有可能吗?
答案 0 :(得分:2)
您可以将奇数索引映射到相应的产品名称:
let oddIndexedProducts = stride(from: 1, through: productsList.count, by: 2)
.map { productsList[$0].name }
print(oddIndexedProducts) // ["BBB", "DD", "EEE", "DSF", "GFDHT"]
另一种方法是在compactMap
序列上使用enumerated()
:
let oddIndexedProducts = productsList.enumerated().compactMap {
$0.offset % 2 == 1 ? $0.element.name : nil
}
根据经验:“ filter + map = compactMap”(在Swift 3中为“ flatMap”)。
答案 1 :(得分:1)
这是一种方法:
print(
productsList
.enumerated()
.filter { $0.offset % 2 == 1 }
.map { $0.element.name }
)
enumerated
方法将每个乘积变成一个2元组,其中包含乘积及其在数组(offset
)中的索引。然后,您filter
仅留下索引为奇数(或偶数)的产品。之后,您需要将2元组映射到产品名称。