Book Image

Mastering Swift

By : Jon Hoffman
Book Image

Mastering Swift

By: Jon Hoffman

Overview of this book

Table of Contents (22 chapters)
Mastering Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Subscripts with Swift arrays


The following example shows how to use subscripts to access and change the values of an array:

var arrayOne = [1,2,3,4,5,6]
println(arrayOne[3])  //Displays '4'
arrayOne[3] = 10
println(arrayOne[3])  //Displays '10'

In the preceding example, we create an array of integers and then use the subscript syntax to display and change the item at element number 3 of the array. Subscripts are mainly used to get or retrieve information from a collection. We generally do not use subscripts when specific logic needs to be applied to determine which item to select. As examples, we will not use subscripts to append an item to the end of the array or to retrieve the number of items in the array. To append an item to the end of an array, or to get the number of items in an array, we will use functions or properties like this:

arrayOne.append(7)  //append 7 to the end of the array
arrayOne.count  //returns the number of items in an array

Subscripts in Swift should follow the standard...