Menu
CoddyTech

Sets and Membership

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

C# HashSet<T> and Swift Set<Element> represent membership without duplicates. Swift elements must be Hashable; C# uses an equality comparer and matching hash codes. Neither collection should be printed in its raw iteration order when output must be deterministic. This example records enabled feature names and removes one feature, then sorts the remaining names. Removing an absent value is harmless. In Swift, insert returns a tuple that includes whether insertion occurred, while C# Add returns a Boolean. This is a membership update example; the exercise asks for an intersection of two integer collections.

C#

Complete program file: Program.cs.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var enabled = new HashSet<string> { "search", "sync", "search" };
        enabled.Remove("sync");
        Console.WriteLine(string.Join(",", enabled.OrderBy(x => x, StringComparer.Ordinal)));
    }
}

Swift

Complete program file: main.swift.

var enabled: Set<String> = ["search", "sync", "search"]
enabled.remove("sync")
print(enabled.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 C# Developers

Practice on your own: Swift playground