How to add an element to an array in Swift? Main methods and examples
Hello! I just started learning Swift and encountered a problem when working with arrays. I need to add a new element to an existing array, but I'm not sure how to do it correctly.
I have an array of strings:
```swift
var fruits = ["Apple", "Banana", "Orange"]
```
I want to add "Grape" to it. I tried several options, but they don't work. For example, I tried:
```swift
fruits.add("Grape") // Error: Value of type '[String]' has no member 'add'
```
Then I tried just assigning a value:
```swift
fruits[3] = "Grape" // Error: Index out of range
```
What am I doing wrong? In other languages, like Java, I used the `add()` method, but in Swift it apparently doesn't work. Please tell me how to correctly add elements to an array in Swift?
No answers yet.
Log in to leave an answer
Blogs