in development, we should be familiar with the concept of arrays, OBJECTIVE-C provides us with Nsarray as an array of implementations. Everyone should be familiar with it. In Swift, we are provided with its own implementation of the array, and here is what we want to introduce, is the array class.
The official documentation for the Array can be see here: swiftstandardlibraryreference
Needless to say, the following is the beginning of our theme.
<!--more--
Create an array
The first thing we want to do with an array is to create it, and thearray class gives us several ways to create it:
var emptyArray = Array <Int> ()
We have declared an empty array here. The elements of the array are of type Int.
var equivalentEmptyArray = [Int] ()
This way of writing has the same effect as the previous one. We can also initialize it like this:
let numericArray = Array (count: 4, repeatedValue: 5)
// the array element is [5,5,5,5]
This initialization method uses 4 numbers to fill the array, and the type of the array element is Int.
Accessing elements of an array
After our array is created, we can refer to its elements by subscripts:
var weekdays = ["monday", "tuesday", "wednesday", "thursday"]
println (weekdays [1]) // print tuesday
We can also modify the elements in the array by subscripting:
var weekdays = ["monday", "tesday", "today", "thursday"]
weekdays [2] = "wednesday"
// Modified array element ["monday", "wednesday", "today", "thursday"]
But we can't modify the constant array defined by the let keyword through subscripts:
let weekdays = ["monday", "tesday", "today", "thursday"]
weekdays [2] = "wednesday" // Report an error
Swift also provides scoped subscript access:
let weekdays = ["monday", "wednesday", "today", "thursday"]
let subdays = weekdays [0 ... 2]
// array elements of subdays ["monday", "wednesday", "today"]
We can use arr [0 ... 2] index of this form to access the elements of a certain area in the array, which can be seen from the above example.
We can even use the range index to set the elements of the array, provided that the array is defined with var:
var weekdays = ["monday", "wednesday", "today", "thursday"]
weekdays [0 ... 1] = ["today", "tomorrow"]
// Elements of the array ["today", "tomorrow", "today", "thursday"]
Swift Tips-Array type