.intersection()
Published Oct 23, 2022
Contribute to Docs
The .intersection()
method returns a new set containing all elements of the set that also belong to the given sequence.
Syntax
newSet = mySet.intersection(mySequence)
Sets mySet
and sequence mySequence
must have a countable number of members.
Example
let friends: Set = ["Pam", "Jim", "Andy", "Darryl"]let colleagues = ["Dwight", "Michael", "Kelly", "Andy", "Darryl"]let workFriends = friends.intersection(colleagues)print(workFriends)let groupAges: Set = [12, 22, 17, 45, 64, 6]let minorAges = (0...17)let children = groupAges.intersection(minorAges)print(children)
This will output:
["Darryl", "Andy"][17, 6, 12]
Note: A set is an unordered data structure, so elements may be ordered differently when outputted.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Swift on Codecademy
- Skill path
Build iOS Apps with SwiftUI
Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.Includes 7 CoursesWith CertificateBeginner Friendly13 hours - Free course
Learn Swift
A powerful programming language developed by Apple for iOS, macOS, and more.Beginner Friendly12 hours