Menu
CoddyTech

Sets and Membership

Lesson 22 of 48 in Coddy's Swift for Ruby Developers course.

Ruby's standard-library Set represents uniqueness using hashing and equality rules. Subtraction removes members found in the other set. Requiring set makes the dependency explicit in a standalone program; the surviving values are sorted before formatting rather than relying on traversal order.

Swift Set<Element> expresses membership directly and requires Hashable elements. Operations include union, intersection and subtracting. Set iteration order should not be used for a stable report; sorted() returns an ordered array when the elements support comparison.

Swift Set requires Hashable elements and offers corresponding set operations. Both examples remove muted features and report the rest alphabetically. Choose arrays when duplicates or positions are meaningful instead of treating every collection as a set.

Complete Ruby comparison program:

require "set"
enabled = Set["search", "sync", "export"]
muted = Set["sync"]
puts((enabled - muted).to_a.sort.join(" "))

Complete Swift comparison program, compiled from these files:

main.swift

let enabled: Set<String> = ["search", "sync", "export"]
let muted: Set<String> = ["sync"]
print(enabled.subtracting(muted).sorted().joined(separator: " "))
challenge icon

Challenge

Easy

Implement overlap(_:_:): return distinct shared integers sorted ascending. Input is two lists separated by one |; each list contains 0 through 30 whitespace-separated integers -100 through 100. Output space-separated shared values or a blank line.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
return overlap([4,4,2],[2,4,4]) == [2,4] && overlap([], [1]) == []
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for Ruby Developers

Practice on your own: Swift playground