Swift String Array

Welcome to Swift Tutorial. In this tutorial, we will learn about Swift String Arrays, how to create them, initialize and access them, etc.

Arrays are important derived datatypes in any functional programming language. Arrays help to store similar type of objects under a single variable name while providing access to the objects using an index.

String Arrays store multiple strings under a single variable name.

While getting started with String Arrays in Swift programming, let us see the syntax to create an empty array.

Create an Empty String Array

To create an empty String Array, use the following syntax.

var array_name = [String]()

array_name is used an identifier to access this String array.

[Int] specifies that this is an array which stores strings.

There is no need to mention the size of an array while creation. The size of an empty String array is 0.

Create a String Array with a default value

Swift allows creating a String Array with a specific size and a default value for each string in the array.

To create a String Array with a specific size and default value, use the following syntax.

var array_name = [String](repeating: default_value, count: array_size)

where

array_size is a number that defines the size of this array.

default_value is the default value for each string in this array.

An example would be

var names = [String](repeating: "tutorialkart", count: 3)

In the above statement, a String Array would be created with a size of 3 and a default value of “tutorialkart” for each item in the array.

Create a String Array with initial values

You can also create a String Array in Swift with initial values. Which means you can combine array declaration and initialization in a single statement.

var names:[String] = ["TutorialKart","Swift Tutorial"]

Note that there is a slight variation in the syntax. The [String] part comes to the left side.

The initial values are enclosed in squared brackets and are separated by a comma.

Access String Array in Swift

Items of the String Array can be accessed using the index.

main.swift

var names:[String] = ["TutorialKart","Swift Tutorial", "iOS Tutorial"]
var name = names[1]
print( "String at index 1 is : \(name)" )

Output

String at index 1 is : Swift Tutorial

Note: The index of an array starts at 0.

From the above example, numbers[0] = 7, numbers[1]=54 and so on.

Following are some the operations that can be performed on String Arrays in Swift.

Conclusion

In this Swift Tutorial, we have learned to declare, initialize, access and other operations on String Arrays in Swift programming.