How to add an element to an array in Swift: complete guide
Hi! I just started learning Swift and ran into a problem: I can't figure out how to properly add elements to an array.
Here's my code:
var fruits = ["apple", "banana"]
fruits.append = "orange" // Error!
fruits += "grape" // Also error
fruits[2] = "kiwi" // And this doesn't work
I tried using different methods, but each time I get compilation errors. It seems I'm confusing the syntax with other languages.
Please tell me, what are the correct ways to add elements to an array? I need:
1. Add one element to the end
2. Add multiple elements at once
3. Insert an element at a specific position
I would be grateful for simple examples with explanations. I'm especially interested in how this works with mutable (var) and immutable arrays. No answers yet.
Log in to leave an answer