Andrew Andrew - 1 month ago 26
Swift Question

Select() from LINQ in swift 3.0?

Is it exist some alternative of LINQ Select() method in the Swift language?

As example, in c# I can do the following:

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


but how I can do the same thing using Swift language?

Answer

map(_:)

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

which is syntactic sugar for:

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

The applied syntactic sugar includes:

  1. Trailing closure syntax

    Transforms the original to

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

    Transforms the previous to

    let ranks = cards.map{ card -> Rank in
        return card.rank
    }
    
  3. Return type inference

    Transforms the previous to

    let ranks = cards.map{ card in
        return card.rank
    }
    
  4. Implicit return value

    Transforms the previous to

    let ranks = cards.map{ card in
       card.rank
    }
    
  5. Anonymous closure arguments

    Transforms the previous to

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

Check out the language guide section on closures (the Swift name for C# Lambdas) for more information,

Comments