Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Set and Higher-Order Functions

Swift Set and Higher-Order Functions

Swift's Set is used to store an unordered collection of unique values, suitable for deduplication and set operations.

Higher-order functions are functions that can take a function as a parameter or return a function as a value; map, filter, and reduce in the standard library all fall into this category.

This article first covers the creation of Set and set operations, then the most commonly used higher-order functions on collection types, and finally demonstrates the chained syntax that strings them together.


Creating a Set

The element type of a Set must conform to the Hashable protocol; Swift's basic types such as Int, String, Double, and Bool all meet this requirement.

A Set can be created directly with an array literal, and duplicate elements are automatically removed.

Example

// Create a Set with an array literal; duplicate elements are automatically removed

var runoobSet

:

Set

<

String

=

[

"Swift"

,

"Kotlin"

,

"Rust"

]

runoobSet.

insert

(

"Go"

)

                 

// Insert an element

print

(

runoobSet.

count

)

                 

// count is the number of elements

print

(

runoobSet.

contains

(

"Swift"

)

)

     

// Check whether it contains a certain element

print

(

runoobSet.

contains

(

"Python"

)

)

print

(

runoobSet.

sorted

(

)

)

             

// Set is unordered; sort before printing for stable output

// Duplicate elements in the array are automatically deduplicated

let repeated

:

Set

<

Int

=

[

1

,

2

,

2

,

3

,

3

,

3

]

print

(

repeated.

sorted

(

)

)



4

true

false

["Go", "Kotlin", "Rust", "Swift"]

[1, 2, 3]

Note that Set is an unordered collection; when you print a Set directly, the order of elements is not fixed and may differ across environments.

To make output stable, call sorted() to arrange into an array before printing; all Set output in this article uses this approach.

Note:Set requires elements to be hashable, so the element type must conform to Hashable. For a struct whose members are all Hashable, the compiler can automatically synthesize the Hashable implementation without writing it by hand.


Adding and Removing Elements and Mutating Set Operations

Set provides methods such as insert and remove to add and remove elements, as well as in-place operations prefixed with form that modify the original collection directly without producing a new one.

Example

// Methods prefixed with form modify in place and do not return a new collection

var s

:

Set

<

Int

=

[

1

,

2

,

3

]

s.

insert

(

4

)

                   

// Insert 4

s.

remove

(

1

)

                   

// Remove 1

s.

formUnion

(

[

5

,

6

]

)

           

// Union operation and write back to s

s.

formIntersection

(

[

2

,

3

,

5

]

)

 

// Intersection operation and write back to s

s.

subtract

(

[

3

]

)

               

// Difference operation and write back to s

print

(

s.

sorted

(

)

)

// remove returns the removed element on success, or nil if the element does not exist

var t

:

Set

<

String

=

[

"RUNOOB"

,

"runoob"

]

print

(

t.

remove

(

"runoob"

)

??

"not found"

)

print

(

t.

remove

(

"www.runoob.com"

)

??

"not found"

)



[2, 5]

runoob

不存在

Set and Array can be freely converted: Set(array) yields a deduplicated set, and Array(set) turns the set back into an array.


Set Operations: Union, Intersection, Difference, and Symmetric Difference

These methods all return a brand-new Set without modifying the original collection; in the table below, a and b represent two sets respectively.

Method Operation Result description
a.union(b) Union All elements that appear in a or b
a.intersection(b) Intersection Elements present in both a and b
a.subtracting(b) Difference Elements in a but not in b
a.symmetricDifference(b) Symmetric difference Elements that appear in only one of the sets

Example

let a

:

Set

<

Int

=

[

1

,

2

,

3

,

4

]

let b

:

Set

<

Int

=

[

3

,

4

,

5

,

6

]

print

(

"Union:"

, a.

union

(

b

)

.

sorted

(

)

)

                 

// All elements from both sides

print

(

"Intersection:"

, a.

intersection

(

b

)

.

sorted

(

)

)

         

// Elements shared by both sides

print

(

"Difference:"

, a.

subtracting

(

b

)

.

sorted

(

)

)

           

// Only in a

print

(

"Symmetric difference:"

, a.

symmetricDifference

(

b

)

.

sorted

(

)

)

 

// Only on one side



并集: [1, 2, 3, 4, 5, 6]

交集: [3, 4]

差集: [1, 2]

对称差: [1, 2, 5, 6]

Symmetric difference can be understood this way: take the union first, then subtract the intersection, and what remains are the elements belonging to only one side.


Subset, Superset, and Disjoint Checks

These methods return a Bool to determine the containment relationship between two sets.

Example

let small

:

Set

<

String

=

[

"Swift"

]

let big

:

Set

<

String

=

[

"Swift"

,

"Kotlin"

,

"Rust"

]

print

(

small.

isSubset

(

of

:

big

)

)

         

// true, all elements of small are in big

print

(

big.

isSuperset

(

of

:

small

)

)

       

// true, big contains all elements of small

print

(

small.

isStrictSubset

(

of

:

big

)

)

   

// true, proper subset: the two sets are not equal

print

(

big.

isDisjoint

(

with

:

[

"Go"

]

)

)

   

// true, no elements in common

// When the two sets are completely equal

let same

:

Set

<

String

=

[

"Swift"

,

"Kotlin"

,

"Rust"

]

print

(

big.

isSubset

(

of

:

same

)

)

         

// true, equal sets count as subsets

print

(

big.

isStrictSubset

(

of

:

same

)

)

   

// false, a proper subset requires inequality



true

true

true

true

true

false

The difference between isSubset and isStrictSubset only shows when the two sets are equal: when equal, the former is true and the latter is false.

Note:An empty set is a subset of any set, and also a subset of itself. To check "whether there are no elements in common", use isDisjoint(with:), rather than taking the detour of checking whether the intersection is empty.


Overview of Higher-Order Functions

The common feature of higher-order functions is that they take a closure as a parameter to describe "what to do with each element".

Higher-order function pipeline: the array passes through map, filter, and reduce in sequence, with the output of each step annotated below that step

The table below lists the eight functions covered in this article; they are all defined on the Sequence or Collection protocols, so arrays, Sets, and dictionaries can all use them.

function Purpose Return Value
map Transform each element into another value according to a rule A new array of equal length
filter Keep elements that satisfy a condition A new array
reduce Combine all elements into a single value A single result
compactMap Transform and discard elements whose result is nil A new array
flatMap Flatten a nested structure by one level A new array
forEach Perform an operation on each element, ignoring the return value Void
sorted Sort according to a rule A new array
contains(where:) Determine whether an element satisfying a condition exists Bool

map and filter

map "turns" each element into another value, and the returned array has the same length as the original collection.

filter is like a sieve, keeping only elements for which the closure returns true.

Example

let numbers

=

[

1

,

2

,

3

,

4

,

5

]

// map: apply a closure to each element, returning a new array of equal length

print

(

numbers.

map

{

$

0

2

}

)

let names

=

[

"runoob"

,

"swift"

]

print

(

names.

map

{

$

0

.

uppercased

(

)

}

)

// filter: keep elements for which the closure returns true

print

(

numbers.

filter

{

$

0

%

2

==

0

}

)

// When map is applied to a Set, the return value is an array, not a Set

let langs

:

Set

<

String

=

[

"Swift"

,

"Go"

,

"Rust"

]

print

(

langs.

map

{

$

0

.

count

}

.

sorted

(

)

)



[2, 4, 6, 8, 10]

["RUNOOB", "SWIFT"]

[2, 4]

[2, 4, 5]

Note that $0 is the shorthand closure parameter, representing the element currently being processed.


reduce for Combining Elements

reduce "folds" a collection into a single value; the first parameter is the initial value, and the closure takes two parameters: the accumulated value and the current element.

Example

let numbers

=

[

1

,

2

,

3

,

4

,

5

]

// Full form: $0 is the accumulated value, $1 is the current element

print

(

numbers.

reduce

(

0

)

{

$

0

$

1

}

)

// Operator function form, with exactly the same effect

print

(

numbers.

reduce

(

0

,

)

)

// Find the maximum: take the first element as the initial value

print

(

numbers.

reduce

(

numbers

[

0

]

)

{

$

0

$

1

?

$

0

:

$

1

}

)



15

15

5

The initial value of reduce determines the result type; for example, giving an empty string as the initial value lets you concatenate an array of strings.


compactMap and flatMap

compactMap discards nil while transforming, while flatMap flattens nested collections into one level.

Example

// compactMap: convert strings to Int; those that cannot be converted return nil and are discarded

let raw

=

[

"1"

,

"2"

,

"runoob"

,

"4"

]

print

(

raw.

compactMap

{

Int

(

$

0

)

}

)

// flatMap: flatten a nested array

let nested

=

[

[

1

,

2

]

,

[

3

,

4

]

,

[

5

]

]

print

(

nested.

flatMap

{

$

0

}

)

// flatMap is also commonly used to split multiple strings by spaces and merge them into one array

let sentences

=

[

"Hello Runoob"

,

"Welcome to RUNOOB"

]

print

(

sentences.

flatMap

{

$

0

.

split

(

separator

:

" "

)

}

)



[1, 2, 4]

[1, 2, 3, 4, 5]

["Hello", "Runoob", "Welcome", "to", "RUNOOB"]

If you use map directly to convert strings to integers, the result will be an [Int?] mixed with nil, and compactMap solves exactly this problem.

Note:Use compactMap when the closure returns an optional. flatMap handles "a collection of collections", while compactMap handles "a collection of optionals"; do not mix them up.


forEach, sorted, and contains(where:)

forEach is used to iterate and perform side effects, sorted returns a new sorted array, and contains(where:) is used for conditional lookup.

Example

let numbers

=

[

1

,

2

,

3

,

4

,

5

]

// forEach: only performs operations, no return value

numbers.

forEach

{

print

(

"Element: ($0)"

)

}

let names

=

[

"runoob"

,

"swift"

]

print

(

names.

sorted

(

)

)

         

// Default ascending order

print

(

numbers.

sorted

(

by

:

)

)

   

// Pass a comparison closure to achieve descending order

// Sort by the second element of the tuple, then retrieve the first element

let sites

=

[

(

"Runoob"

,

2014

)

,

(

"Google"

,

1998

)

,

(

"Apple"

,

1976

)

]

print

(

sites.

sorted

{

$

0.1

<

$

1.1

}

.

map

{

$

0.0

}

)

// contains(where:): whether an element satisfying the condition exists

print

(

numbers.

contains

(

where

:

{

$

0

4

}

)

)

print

(

numbers.

contains

(

where

:

{

$

0

100

}

)

)



元素: 1

元素: 2

元素: 3

元素: 4

元素: 5

["runoob", "swift"]

[5, 4, 3, 2, 1]

["Apple", "Google", "Runoob"]

true

false

sorted always returns a new sorted array and does not modify the original collection; when the original order needs to be preserved, just use the return value.


Chained Calls

These higher-order functions all return an array or a single value, so they can be chained one after another, with each step only concerned about the output of the previous step.

Example

// First filter out even numbers, then square them, and finally sum them

let result

=

(

1

...

10

)

    .

filter

{

$

0

%

2

==

0

}

 

// 2 4 6 8 10

    .

map

{

$

0

$

0

}

         

// 4 16 36 64 100

    .

reduce

(

0

,

)

           

// Accumulate

print

(

result

)

// Use Set to deduplicate, then convert to uppercase, sort, and concatenate into a string

let words

=

[

"Swift"

,

"Kotlin"

,

"Swift"

,

"Rust"

]

let summary

=

Set

(

words

)

    .

map

{

$

0

.

uppercased

(

)

}

    .

sorted

(

)

    .

joined

(

separator

:

", "

)

print

(

summary

)



220

KOTLIN, RUST, SWIFT

The readability of chained syntax comes from "one thing per line"; if you cram three closures into a single line, it is better to split them into several variables.


Common questions

Below are the questions most often asked when learning Set and higher-order functions.

Which should you choose, Set or Array

Use Set when you need deduplication, containment checks, or set operations; use Array when you need to preserve order or allow duplicate elements.

Set lookup is constant time complexity; when there are many elements and you frequently check "whether something exists", Set is much faster than Array.

What is the difference between map and forEach

map has a return value, transforming each element and collecting them into a new array; forEach has no return value and is only used to perform operations with side effects, such as printing or writing files.

If the result does not need to be kept, forEach is clearer semantically; if you need a new array, you must use map.

Why is the printing order of a Set different every time

Set is stored internally with a hash table, and element order is determined jointly by hash values and capacity; the official documentation does not guarantee iteration order.

When stable output is needed, call sorted() first, or switch to Array in cases where order truly matters.

What to do to put a custom type into a Set

Just make the type conform to the Hashable protocol. If all its stored properties are Hashable, the compiler will synthesize the implementation automatically.

Once you write == or hash(into:) by hand, you must ensure that two equal instances have the same hash value, otherwise the Set will contain duplicate elements.