Menu
CoddyTech

Sets and Membership

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

A Luau table with truthy membership markers can implement a set. Reassigning the same key does not add a duplicate, and assigning nil removes membership. This example counts keys with pairs instead of treating a string-keyed table as a dense sequence.

Swift Set requires Hashable elements and represents uniqueness directly. Removing write leaves one read member despite the duplicate read in the literal. A set has no stable ascending iteration contract; sort for a deterministic textual report. Use arrays instead when positions or repeated entries matter.

Luau

Complete Luau console program:

main.luau

local capabilities = {read = true, write = true}
capabilities.read = true
capabilities.write = nil
local count = 0
for _ in pairs(capabilities) do count += 1 end
print(tostring(capabilities.read == true) .. " " .. count)

Swift

Complete program; compile the listed files together:

main.swift

import Foundation
var capabilities: Set<String> = ["read", "write", "read"]
capabilities.remove("write")
print(capabilities.contains("read"), capabilities.count)
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 Luau Developers

Practice on your own: Swift playground