从swq 3.0中的LINQ中选择()?

时间:2016-11-02 21:50:27

标签: swift linq

在Swift语言中是否存在LINQ Select()方法的替代方法?

例如,在c#中,我可以执行以下操作:

var ranks = cards.Select(a=> a.Rank).ToArray();

但我如何使用Swift语言做同样的事情?

1 个答案:

答案 0 :(得分:5)

map(_:)

let ranks = cards.map{ $0.Rank }

这是语法糖:

let ranks = cards.map({ (card: Card) -> Rank in
    return card.rank
})

应用的语法糖包括:

  1. Trailing closure syntax

    let ranks = cards.map { (card: Card) -> Rank in
        return card.rank
    }
    
  2. 参数类型推断

    let ranks = cards.map { card -> Rank in
        return card.rank
    }
    
  3. 返回类型推断

    let ranks = cards.map { card in
        return card.rank
    }
    
  4. 隐含返回值

    let ranks = cards.map { card in
       card.rank
    }
    
  5. 匿名闭包参数

    let ranks = cards.map { $0.rank }
    
  6. 查看language guide section on closures(用于C#调用 lambdas 的Swift名称)以获取更多信息,