Swift - Extract values from an array

Introduction

Suppose you have the following array of names:

let names = ["Jason", "Jacob", "Nathan", "Java", "Jane", "Truckter", "Jayden", "Ryan"]

To extract all the names that contain the word "an."

You can use the filter() function with the following closure:

Demo

let names = ["Jason", "Jacob", "Nathan", "Java", "Jane", "Truckter", "Jayden", "Ryan"]
var someNames = names.filter(
    {//from ww  w. j a v  a2  s  .  co  m
          (name:String) in
              (name as NSString).containsString("an")
    }
)
print(someNames)

Using shorthand argument naming, the closure can be reduced to the following:

let names = ["Jason", "Jacob", "Nathan", "Java", "Jane", "Truckter", "Jayden", "Ryan"]

var someNames = names.filter(
     {
         ($0 as NSString).containsString("an")
     }
)
print(someNames)

Related Example