Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
map
set
communitycreator

How to map a set in Swift

Theodore Kelechukwu Onyejiaku

Overview

In Swift, we can use the map{} method on a set to return an array that corresponds to what was specified in a block. For example, we can use this method to return the results of dividing each number value of a set by 2.

Syntax

set.map{closure}
Syntax of the "map{}" method in Swift

Parameter value

Closure: This value creates a condition or a closure over the set's elements. It also gives us access to each element of the set.

Return value

This method returns an array.

Example

// create some sets
let names: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let numbers: Set = [1, 2, 3, 4, 5, 7, 8, 9, 10]

// use the map{}
print(names.map{$0.count}) // return array of length of names
print(numbers.map{$0 * 2}) // return array of numbers multiplied by 2
Using the "map{}" method on a set in Swift

Explanation

  • Lines 2–3: We create some sets and initialize them with values.
  • Line 6: We map the names set and return an array that contains the count of characters of each name.
  • Line 7: We use the map{} method to return an array of elements of the numbers set, where each element in the array has been multiplied by 2.

RELATED TAGS

swift
map
set
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring