We have to use append(_:) for an Array and insert(_:) for a Set. Therefore, if you define them as constants using let you’ll run into the following error when you try to add an object: An error showing that the Array and Set are immutableĪs you can see in the above image we have our first difference here. Adding objectsīoth Arrays and Sets are value types.
This is important to take into account when picking your choice. Printing out the collections after initialization confirms this: print(arrayOfBlogCategories) // In other words, a Set is unordered while an Array is keeping its order. You can use a set instead of an array when the order of items is not important, or when you need to ensure that an item only appears once. Take a look at the following quote from the documentation:Ī set stores distinct values of the same type in a collection with no defined ordering.
#Object array vs arraylist code
Using the following code will end up in an Array of Strings: let blogCategories = // Defaults to ArrayĪt first, you might think that both collections are exactly the same after initialization. Let setOfBlogCategories: Set = īoth types support the same ExpressibleByArrayLiteral protocol although it’s good to know that the Array Literal type defaults to an Array. When we compare the initialization of Arrays and Sets we can really see that they’re quite the same. Get started with 2 free months of Sentry’s Business Plan (the best one) with code: SWIFTLEE Initialization Increase your application's performance with rich context about errors and slowdowns in your iOS applications.
Keep your iOS Applications Performant (and your users happy)