Menu
CoddyTech

Sets and Membership

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

Go often models a set with map[T]struct{} when only key membership matters. Swift Set provides a dedicated unique-membership value type whose elements conform to Hashable. Go map keys must be comparable, which is a different constraint system.

Both examples remove write and retain read. A Go copied map value continues to share its storage, while a Swift Set copy preserves independent value semantics. Repeated insertion of a key does not create duplicate members in either representation.

Go: complete program

main.go

package main
import (
    "fmt"
)

func main() {
permissions := map[string]struct{}{"read": {}, "write": {}}
    delete(permissions, "write")
    _, present := permissions["write"]
    fmt.Println(present, len(permissions))
}

Swift: complete program

main.swift

import Foundation
var permissions: Set<String> = ["read", "write"]
permissions.remove("write")
print("\(permissions.contains("write")) \(permissions.count)")

Neither membership representation promises sorted display order. Explicitly sort a sequence of members when output must be deterministic.

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 Go Developers

Practice on your own: Swift playground