Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 61 / 68

Set operations with NSSet (union, intersection, difference)

This lesson covers unions, intersections, and differences with NSMutableSet in Objective-C, with the aim of understanding the basics of set operations.

NSMutableSet provides unionSet:, intersectSet:, and minusSet:, which calculate the union, the intersection, and the difference respectively.

The sample code takes the two sets {1, 2, 3, 4} and {3, 4, 5, 6}, makes copies with mutableCopy, and applies each method to show the union, intersection, and difference.

A common early stumble is that these methods change the set they are called on. To keep the original data you first make a copy with mutableCopy, as the sample does.

It is a useful way of thinking for real data work — finding the users in both groups — and intersections and differences also help in understanding SQL joins.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Objective-C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)