UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Project 2: Question on Array Assignment

Forums > 100 Days of Swift

In Project 2, we have the following:

var countries = [String]()

countries += ["estonia", "france", "germany", "ireland", "italy", "monaco", "nigeria", "poland", "russia", "spain", "uk", "us"]

Why is there a need for the += operator? It could just as easily have been written:

countries = ["estonia", "france", "germany", "ireland", "italy", "monaco", "nigeria", "poland", "russia", "spain", "uk", "us"]

3      

Dunno, lots of things can be accomplished in a lots of ways.. Maybe Paul wanted to show how to append multiple items to an array..

3      

Following on from nemecek the way you choose will depend on what your using it for.

For example. If you are just adding that array of strings to the empty country array once then = would be fine, but if you were appending items to that array multiple times throughout your code then you would use the +=

Hope this clears it up

Dave

3      

Thank you @nemecek-filip & @Newy11527. I do understand you would use += for append operations, that makes total sense. But, since this was initial assignment that populates the array fully, the standard = is what comes to my mind to use.

So I was asking this question mainly to know Paul's reason for using +=. Maybe there's a really good reason to do so that I need to learn.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.