The append()
method adds single or multiple elements to an array in Swift. It is invoked by an array. We use append(_:)
to add a single element. Alternatively, we use append(contentsOf:)
if we want to add a multiple.
// single element arr.append(element) // multiple element arr.append(contentsOf: [element1, element2...])
element
: This is the single element we want to append to the arr
array.
[element1, element2,...]
: This is an array of elements we want to append to the arr
array.
A new array with newly appended elements is returned.
// create an array var languages = ["Java", "C++", "Python"] // append a single element languages.append("Perl") // append multiple elements languages.append(contentsOf: ["Ruby", "Swift"]) // print array values for lang in languages{ print(lang) }
languages
.for-in
loop prints each element of the array.RELATED TAGS
CONTRIBUTOR
View all Courses