I am trying to understand Sets in Swift and how to declare them correctly but I have found the following a little confusing.
I understand that this works:
let elements = [ 1, 2, 3, 4, 5, 1, 2, 6, 7]
let setFromElements = Set(elements)
But I don't understand why the following doesn't:
let setFromElements : Set = elements
Or even:
let setFromElements : Set<Int> = elements
When the following is valid:
let setFromArray : Set = [ 1, 2, 4, 5]
Can someone please help me understand why this is the case?
CodePudding user response:
let setFromArray: Set = [ 1, 2, 4, 5]
works because Set
conforms to ExpressibleByArrayLiteral
and hence has an initializer that takes an ArrayLiteral
. See Set.init(arrayLiteral:)
. This conformance gives syntactic sugar for not having to explicitly call the init.
On the other hand, once you save the array literal into a variable using let elements = [ 1, 2, 3, 4, 5, 1, 2, 6, 7]
, elements
becomes an Array
, not an ArrayLiteral
and hence another initializer of Set
has to be called that takes an Array
. This init does not provide syntactic sugar like ExpressibleByArrayLiteral
does, so you explicitly have to call the init by doing Set(array)
.
CodePudding user response:
Set has an initializer that takes an array, and that makes a set, by taking the unique items in the array. But a set is not an array, two different types, so you can't just use =
to assign one to the other.