[Swift learning] Swift programming tour-array of Collection types (6), swift tour

Source: Internet
Author: User

[Swift learning] Swift programming tour-array of Collection types (6), swift tour

Swift provides three main collection types: array, set, and dictionary. This section describes array.


An array is a set of the same type of storage order. The same value can appear in different positions multiple times.


Swift's Array-type bridging Foundation's NSArray class


Simple Syntax of array type

Swift Array type full writing Array <Element>, Element is the legal type of the Array that allows storing values, you can also simply write [Element]. Although the two forms are the same in terms of functionality, we recommend the shorter ones, and this form will be used in this article to use arrays.


  1. Create an array

1. Create an empty array

Note that the someInts variable type is inferred to be an int type during initialization, or if the context already provides type information, for example, if a function parameter or a constant or variable of the defined type is used, you can directly write [] without adding an Int.

someInts.append(3)// someInts now contains 1 value of type IntsomeInts = []// someInts is now an empty array, but is still of type [Int]

3. Create an array with default values

The Array type in Swift also provides a constructor that can create a specific size and set all data to the same default value. We can pass the number of items to be added to the array (count) and the initial value of the appropriate type (repeatedValue) into the array constructor:

var threeDoubles = [Double](count: 3, repeatedValue: 0.0)// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]


A 4.2-digit combination and an array

+ Is used to combine two numbers into a new array.

var anotherThreeDoubles = [Double](count: 3, repeatedValue: 2.5)// anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5] var sixDoubles = threeDoubles + anotherThreeDoubles// sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]


5. [value 1, value 2, value 3]

var shoppingList: [String] = ["Eggs", "Milk"]


ShoppingList is an array variable that stores the String type and can only store values of the String type. It also supports Simple Writing.

var shoppingList = ["Eggs", "Milk"]


 2. Access and modification of Arrays

We can access and modify the array or subscript syntax through array methods and attributes. Use the read-only attribute count of the array to obtain the count of the array.

print("The shopping list contains \(shoppingList.count) items.")// Prints "The shopping list contains 2 items.


Use isEmpty to determine whether the array is empty.


1. Get array data

Subscript Method

var firstItem = shoppingList[0]// firstItem is equal to "Eggs


2. Add data

Use the append (_ :) method to add a new data entry at the end of the array.



You can add several new data entries to the array by using + =.

shoppingList += ["Baking Powder"]// shoppingList now contains 4 itemsshoppingList += ["Chocolate Spread", "Cheese", "Butter"]// shoppingList now contains 7 items


Insert (_: atIndex :) to insert new data at the specified position

shoppingList.insert("Maple Syrup", atIndex: 0)// shoppingList now contains 7 items// "Maple Syrup" is now the first item in the list



3. Modify the Array

Subscript method to modify a value

shoppingList[0] = "Six eggs”


You can also modify the value in the specified range.

shoppingList[4...6] = ["Bananas", "Apples"]// shoppingList now contains 6 items


We cannot use the subscript method to add new data at the end of the array, because the index is invalid after the length of the array is exceeded, and a runtime error may occur.


RemoveAtIndex (_ :) deletes data at the specified position in the array

let mapleSyrup = shoppingList.removeAtIndex(0)// the item that was at index 0 has just been removed// shoppingList now contains 6 items, and no Maple Syrup// the mapleSyrup constant is now equal to the removed "Maple Syrup" string”


If you want to delete the last row of data in the array, you should use removeLast () instead of removeAtIndex () because it does not need to query the length of the array.


  Iv. array Traversal

You can use the for-in' loop to traverse the array.

for item in shoppingList {    print(item)}


If we need the value and index value of each data item at the same time, we can use the global enumerate function to traverse the array. Enumerate returns a key-value pair group consisting of the index value and data value of each data item. We can extract this key-Value Pair component into a temporary constant or variable for traversal:

for (index, value) in shoppingList.enumerate() {    print("Item \(index + 1): \(value)")}// Item 1: Six eggs// Item 2: Milk// Item 3: Flour// Item 4: Baking Powder// Item 5: Bananas”


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.