Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift – Declaring a Set using named variable

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading