Complete the code to create an empty set of integers.
var numbers: Set<Int> = [1]In Swift, an empty set is created using Set(). Using [] creates an empty array, and {} is not valid syntax for an empty set.
Complete the code to create a set with the elements 1, 2, and 3.
let digits: Set<Int> = [1]To create a set with elements, you can pass an array to the Set initializer like Set([1, 2, 3]). Using just square brackets creates an array, and Set(1, 2, 3) is invalid syntax.
Fix the error in the code to check if two sets have any common elements.
let setA: Set<Int> = Set([1, 2, 3]) let setB: Set<Int> = Set([3, 4, 5]) let hasCommon = !setA.[1](setB).isEmpty
The intersection method returns the common elements between two sets. Checking if this intersection is not empty tells us if they share any elements.
Fill both blanks to create a set of even numbers from 1 to 10.
let numbers = Set(1...10) let evenNumbers = numbers.filter { $0 [1] 2 [2] 0 }
To find even numbers, use the modulo operator % to check if the remainder when divided by 2 is zero.
Fill all three blanks to create a dictionary from a set of words with their lengths, but only include words longer than 3 characters.
let words: Set<String> = Set(["apple", "cat", "banana", "dog"]) let wordLengths = [[1]: [2] for [3] in words if [2] > 3]
We create a dictionary where keys are words and values are their lengths. We iterate over each word in the set and include only those with length greater than 3.