Sets and Membership
Lesson 22 of 48 in Coddy's Swift for Rust Developers course.
Rust HashSet requires hashing and equality for its elements, while Swift Set requires Hashable, which includes equality behavior. Both represent uniqueness rather than sequence positions. Rust difference yields an iterator over borrowed members; this example copies the integer results into a vector before sorting. Swift subtracting returns a set and sorted produces an ordered array. The duplicate four does not create a second member, and removing four leaves one and seven. Do not rely on hash iteration order for a report, and avoid mutating the hash-relevant identity of objects while they participate as keys or members.
Rust
fn main() {
use std::collections::HashSet;
let candidates: HashSet<i32> = [4, 1, 4, 7].into_iter().collect();
let excluded = HashSet::from([4]);
let mut allowed: Vec<i32> = candidates.difference(&excluded).copied().collect();
allowed.sort();
println!("{}", allowed.iter().map(i32::to_string).collect::<Vec<_>>().join(" "));
}
Swift
let candidates: Set<Int> = [4, 1, 4, 7]
let allowed = candidates.subtracting([4])
print(allowed.sorted().map(String.init).joined(separator: " "))Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for Rust Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry Rules5Collection Tools
Dictionaries and Missing KeysSets and MembershipUnicode and Character IndicesClosures and TransformationsRecap: Catalog MergePractice on your own: Swift playground