Swift Array Transformation Examples

Swift Array Transformation Examples

This article is part of the following playlists:


Just some examples of some of the built-in methods you can call on a swift array.

Let’s start with some data. A sentence that is split into an array of words.

let quote = "What I cannot create, I do not understand."
let words = quote.split(separator: " ")
// ["What", "I", "cannot", "create,", "I", "do", "not", "understand."]

forEach

Execute a closure once for each item in an array.

let wordLengths = words.forEach { word in
  print(word)
}

map

Create a new array based on an existing array.

let wordLengths = words.map { word in
  return word.count
}
// [4, 1, 6, 7, 1, 2, 3, 11]

filter

Create a new array that is a subset of the items from an existing array.

let largeWords = words.filter { word in
  return word.count > 3
}
// ["What", "cannot", "create,", "understand."]

sorted

Create a new array that is the sorted version of an existing array.

let largestToSmallest = words.sorted { word1, word2 in
  return word1.count > word2.count
}
// ["understand.", "create,", "cannot", "What", "not", "do", "I", "I"]

reduce

Create a new single value based on the values inside an array.

let totalLetters = words.reduce(0) { result, word in
  return result + word.count
}
// 35
// Won't include any whitespace characters

Find an issue with this page? Fix it on GitHub