2

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?

Andrew_STOP_RU_WAR_IN_UA
  • 9,318
  • 5
  • 65
  • 101
  • The `Rank` property of `Card` should be called `rank`, in line with Swift naming conventions. C# uses capitals for properties, and lowercase (or `_` prefix) for instance variables. Swift doesn't have instance variables, so there's no need for the distinction. Properties areLowerCamelCase, and capital camel case is reserved for types and static properties – Alexander Nov 02 '16 at 22:03

1 Answers1

6

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

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

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

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

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

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

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

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • Looks like this is it! Thanks a lot. – Andrew_STOP_RU_WAR_IN_UA Nov 02 '16 at 21:56
  • @Andrew I gave break down of how the various syntactic sugars are applied to reach the final form I showed. It's covered in the language guide. You should definitely read it, it's very well written, and will be a breeze to understand if you already know C#. – Alexander Nov 02 '16 at 22:06