在Swift语言中是否存在LINQ Select()方法的替代方法?
例如,在c#中,我可以执行以下操作:
var ranks = cards.Select(a=> a.Rank).ToArray();
但我如何使用Swift语言做同样的事情?
答案 0 :(得分:5)
map(_:)
let ranks = cards.map{ $0.Rank }
这是语法糖:
let ranks = cards.map({ (card: Card) -> Rank in
return card.rank
})
应用的语法糖包括:
let ranks = cards.map { (card: Card) -> Rank in
return card.rank
}
参数类型推断
let ranks = cards.map { card -> Rank in
return card.rank
}
返回类型推断
let ranks = cards.map { card in
return card.rank
}
隐含返回值
let ranks = cards.map { card in
card.rank
}
匿名闭包参数
let ranks = cards.map { $0.rank }
查看language guide section on closures(用于C#调用 lambdas 的Swift名称)以获取更多信息,