我有一个如下所示的快速代码
var items: [Item] = []
for i in 0...20 {
items.append( makeItem(atIndex: i) )
}
是否可以像上面那样重写
var items: [Item] = [0...20].map {
makeItem(atIndex: i)
}
答案 0 :(得分:3)
有可能,只是不将范围包装在数组中,所以使用(0...20)
代替[0...20]
您甚至可以传递函数的名称,而无需一次调用就创建一个闭包。
let items = (0...20).map(makeItem)
答案 1 :(得分:1)
语法[0...20]
是一个包含Int
的单个封闭范围的数组,不是一个Int数组(这就是您要通常想在上调用map()
,所以您真正想要的是:
let integers = [
0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16,
17 ,18, 19, 20]
integers.map{
// your code here
}
(我的原始答案没有这个区别,我现在已更正。请参见有关如何将范围转换为Int
数组的其他答案)
两者都将在括号内执行该块21次,对数组中的每个整数执行一次。
但是与for
循环相反,map()
函数有望返回某种类型的数组,其中每个元素都是通过转换每个元素而获得的在原始数组中(在这种情况下,是整数0
到20
)进入结果类型的实例。例如:
let textRepresentations: [String] = integers.map {
return "\($0)"
}
// Now textRepresentations contains "0", "1", etc.
如果您的目标是从基于这21个整数创建的对象中组装一个数组,那么map()
会比在更“ C-喜欢”的方式,例如:
var textRepresentations: [String] = []
for i in 0 ... 20 {
textRepresentations.append("\(i)")
}
但是,如果您只需要为这些整数中的每个整数执行一次逻辑,结果就不留任何数组,那么使用map()
(并丢弃结果)将很尴尬,并且使人们不得不混淆代码(包括您的未来自我)。
此外,for ... in
循环的另一个“快速”替代方法是foreach
(看起来更像map()
,减去返回的数组):
integers.foreach {
// (use $0 instead of i)
}
...or, more verbosely:
integers.foreach { (element) in
// (use `element`, of course)
}
答案 2 :(得分:0)
要获取确切的语法,可以创建扩展名:
from lecture.MainObject import computeShippingCost
class Testing(object):
def Test(self):
assert computeShippingCost(20) == 3 #incorrect
assert computeShippingCost(-30) == -8 #incorrect
assert computeShippingCost(40) == -20 #incorrect
assert computeShippingCost(50) == 10 #correct
并这样称呼它:
extension Array where Element == ClosedRange<Int> {
@discardableResult
func map(_ f: @escaping(Int) -> Void) -> [Int]{
var result : [Int] = []
for i in 0 ..< self[0].count {
result.append(i)
f(i)
}
return result
}
}
请注意,当您只想编写如下的let items = [0...50].map {
print($0) // current index
}
print(items)
循环时,项目将为[Int]
,这会在编辑之前 解决您的问题:
for