Create An Array Of String In Swift
Code snippet for how to Create An Array Of String In Swift with sample and detail explanation
An array is a collection of data that holds multiple items of the same type. In Swift, you can create an array of any data type, including strings.
Code snippet for Creating an Array of String in Swift
Here is a simple code snippet to create an array of string in Swift:
var fruits: [String] = ["Apple", "Banana", "Cherry"]
And, if you want to add more elements to the array, you can use the append method:
fruits.append("Dragon Fruit")
Now, “Dragon Fruit” is added to the end of the ‘fruits’ array.
Code Explanation for Creating an Array of String in Swift
Let’s break down each line of the code we just wrote:
var fruits: [String] = ["Apple", "Banana", "Cherry"]
In Swift, arrays are ordered collections of values. Here, we start defining our array with the var keyword because we want it to be mutable, meaning we can change it by adding, removing, or altering its items. Then, we assign it the fruits name and specify the type of values it can contains — [String].
On the right side of the equals sign, we’re initializing our array with three fruit names: “Apple”, “Banana”, “Cherry”. Swift understands that [“Apple”, “Banana”, “Cherry”] is an array of strings since it’s assigned to a variable of type [String]
.
fruits.append("Dragon Fruit")
Here, we use the append method of Swift arrays to add a new item — “Dragon Fruit” — to the end of the array. After this line executes, our ‘fruits’ array contains four elements: “Apple”, “Banana”, “Cherry”, and “Dragon Fruit”.
In this article, we’ve learnt how to create a simple array of strings in Swift and add new elements to it. This allows you to store and manipulate a collection of similar items easily and efficiently. Happy coding!