Swift String Array
A Swift String Array stores an ordered collection of String values. You can create an empty array, initialize it with values, access strings by index, and use array methods to add, update, search, sort, or remove elements.
Swift arrays are type-safe. A value declared as [String] can contain strings, but it cannot contain integers or values of unrelated types. Arrays also preserve the order in which elements are stored and allow duplicate strings.
Create an Empty String Array in Swift
To create an empty String Array, use the following syntax.
var array_name = [String]()
array_name is the identifier used to access the array. The [String] type specifies that the array stores string values.
You do not specify a fixed capacity when creating a normal Swift array. The initial number of elements in an empty array is 0, and the array grows as strings are appended.
You can write the same declaration with an explicit type annotation or with the generic Array<String> form.
var names: [String] = []
var cities = Array<String>()
Create a Swift String Array with a Default Value and Size
Swift allows creating a String Array with a specific number of elements and the same initial value for each element.
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)
Here, array_size is the number of elements to create, and default_value is assigned to every position in the array.
An example would be
var names = [String](repeating: "tutorialkart", count: 3)
This statement creates a String Array containing three elements, each initialized with "tutorialkart".
The count argument must not be negative. A count of 0 creates an empty array.
Create a Swift String Array with Initial Values
You can declare and initialize a String Array in one statement by placing comma-separated string values inside square brackets.
var names:[String] = ["TutorialKart","Swift Tutorial"]
The [String] annotation appears after the variable name. Swift can also infer the element type when every value in the array literal is a string.
var languages = ["Swift", "Kotlin", "Java"]
Use var when the array or its elements must change. Use let when the array must remain unchanged after initialization.
let weekdays = ["Monday", "Tuesday", "Wednesday"]
Access String Array Elements by Index
Items in a String Array can be accessed using an integer index. Swift array indexing starts at 0, so the first element is at index 0, the second at index 1, and so on.
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
For this array, names[0] is "TutorialKart", names[1] is "Swift Tutorial", and names[2] is "iOS Tutorial".
Accessing an index outside the array’s valid range causes a runtime error. Check the index before reading an element when the index may come from user input or another variable.
let index = 2
if names.indices.contains(index) {
print(names[index])
} else {
print("Index is outside the array")
}
Read the First and Last Strings Safely
The first and last properties return optional strings. They return nil when the array is empty, which makes them safer than directly using array[0] or array[array.count - 1].
let names = ["Asha", "Ravi", "Meera"]
if let firstName = names.first {
print("First: \(firstName)")
}
if let lastName = names.last {
print("Last: \(lastName)")
}
Add Strings with append, insert, and +=
Use append(_:) to add one string at the end, append(contentsOf:) or += to add several strings, and insert(_:at:) to place a string at a specific valid index.
var fruits = ["Apple", "Banana"]
fruits.append("Mango")
fruits += ["Orange", "Grapes"]
fruits.insert("Guava", at: 1)
print(fruits)
["Apple", "Guava", "Banana", "Mango", "Orange", "Grapes"]
Update and Remove Strings from an Array
Assign a new value at a valid index to replace one string. Use removal methods such as remove(at:), removeFirst(), removeLast(), or removeAll() depending on which elements should be deleted.
var colors = ["Red", "Green", "Blue"]
colors[1] = "Yellow"
let removedColor = colors.remove(at: 0)
print(colors)
print("Removed: \(removedColor)")
["Yellow", "Blue"]
Removed: Red
Methods such as removeFirst() and removeLast() require a non-empty array. Check isEmpty first when the array might not contain any strings.
Loop Through a Swift String Array
A for-in loop reads each string in array order. Use enumerated() when both the zero-based offset and the string are needed.
let languages = ["Swift", "Kotlin", "Java"]
for language in languages {
print(language)
}
for (index, language) in languages.enumerated() {
print("\(index): \(language)")
}
Check Count, Empty State, and String Membership
Use count for the number of elements, isEmpty to test whether the array contains no strings, and contains(_:) to check for an exact value.
let roles = ["Admin", "Editor", "Viewer"]
print(roles.count)
print(roles.isEmpty)
print(roles.contains("Editor"))
3
false
true
String comparison is case-sensitive by default. For example, roles.contains("editor") is false when the stored value is "Editor".
Sort, Filter, Map, and Prefix String Arrays
Swift array methods can transform or select strings without manually managing indexes. The following example sorts names, filters names beginning with a letter, converts values to uppercase, and reads the first two elements.
let names = ["Meera", "Asha", "Mohan", "Ravi"]
let sortedNames = names.sorted()
let namesStartingWithM = names.filter { $0.hasPrefix("M") }
let uppercaseNames = names.map { $0.uppercased() }
let firstTwo = Array(names.prefix(2))
print(sortedNames)
print(namesStartingWithM)
print(uppercaseNames)
print(firstTwo)
["Asha", "Meera", "Mohan", "Ravi"]
["Meera", "Mohan"]
["MEERA", "ASHA", "MOHAN", "RAVI"]
["Meera", "Asha"]
sorted(), filter(_:), and map(_:) return new arrays and leave the original array unchanged. Use sort() when a mutable array should be reordered in place. The prefix(_:) method returns a subsequence, so wrap it with Array(...) when a separate [String] value is required.
Common Swift String Array Mistakes
- Using an invalid index: valid indexes run from
startIndexup to, but not including,endIndex. - Editing an array declared with let: declare it with
varwhen strings must be added, replaced, or removed. - Expecting case-insensitive matching: methods such as
contains(_:)compare strings using their normal equality rules. - Assuming prefix returns [String]: convert the returned subsequence with
Array(array.prefix(n))when an array is needed. - Removing from an empty array: check
isEmptybefore calling removal methods that require an element.
Related Swift Array Operations
These tutorials cover common operations that build on the String Array examples above.
- Append a String to the array in Swift
- Check if an array is empty in Swift
- Append or Concatenate two arrays
For the complete collection type rules and API details, refer to the Swift Programming Language guide to collection types and the Apple Array documentation.
Swift String Array FAQs
How do I create an empty array of strings in Swift?
Use var names = [String]() or var names: [String] = []. Both declarations create an empty mutable String Array.
How do I create a Swift String Array of a fixed initial size?
Use [String](repeating: value, count: size). For example, [String](repeating: "", count: 5) creates five empty strings. The array is still resizable when declared with var.
How do I safely access a String Array element?
Check array.indices.contains(index) before using array[index]. For the first or last element, prefer the optional first and last properties.
How do I check whether a Swift String Array contains a value?
Call array.contains("value"). The comparison is case-sensitive, so normalize the strings first when case should be ignored.
How do I get the first few strings from an array?
Use array.prefix(n). Convert the result to an array with Array(array.prefix(n)) when the receiving code requires a [String].
Swift String Array Editorial QA Checklist
- Verify every sample stores only
Stringvalues and uses valid Swift syntax. - Confirm examples explain that Swift arrays use zero-based indexing.
- Check that index-based access includes a warning about out-of-range runtime errors.
- Ensure new code blocks use
language-swift,syntax, oroutputclasses as appropriate. - Confirm examples distinguish mutating methods such as
appendandsortfrom non-mutating methods such assorted,filter, andmap.
Swift String Array Summary
In this Swift Tutorial, you learned how to declare and initialize String Arrays, access elements safely, add or remove strings, iterate through values, test membership, and use common transformations such as sorting, filtering, mapping, and taking a prefix.
TutorialKart.com