Sets and Membership
Lesson 22 of 48 in Coddy's Swift for Dart Developers course.
Dart Set and Swift Set store unique elements and support membership and set operations. Swift elements must conform to Hashable; Dart uses equality and hash codes. Never mutate state used for hashing while an object is stored as a key or set member. Swift sets have value semantics. Their iteration order is unspecified, so sort comparable elements before producing ordered output. The example computes elements that occur in exactly one set using symmetric difference, which differs from finding shared elements.
Complete Dart program. Each labelled block is a separate file.
main.dart
void main() {
final left = {1, 3};
final right = {3, 5};
final unique = {...left.difference(right), ...right.difference(left)};
print((unique.toList()..sort()).join(','));
}Complete Swift program. Each labelled block is a separate file.
main.swift
import Foundation
let left: Set<Int> = [1, 3]
let right: Set<Int> = [3, 5]
let unique = left.symmetricDifference(right)
print(unique.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 Dart 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