related articles
Swift Quick Start (1) The first Swift program
Swift Quick Start (2) Basic data types
Swift Quick Start (3) Operator
Swift Quick Start (4) Process Control
Foreword
Swift provides two collection types of arrays and dictionaries to store data. Swift arrays are used to store types with the same order and the same type. Dictionaries use kay-value to store data.
1. Array
Arrays are used to store multiple data of the same data type, and array elements can usually be accessed by their index.
Declare array
There are two syntaxes for declaring an array:
Use generic syntax. The format is: Array <type>
Use simplified syntax. The format is: [Type]
// declare array using generic syntax
var arr: Array <String>
// declare the array using simplified syntax
var names: [String]
Create array
There are also two ways to create an array:
1. Use the Array constructor to create an array
2. Create array using simplified syntax
// Create an empty array and assign the empty array to the myArr variable
arr = Array <String> ()
// Create an array containing 10 "moon" elements and assign the array to the names variable
names = Array <String> (count: 10, repeatedValue: "moon")
// Use simplified syntax to create an array and assign the array to the values variable
var values = ["2", "3", "3", "4", "5", "6"]
Traverse the array
Ordinary loop through the array:
for var i = 0; i <values .count; i ++
{
print (values [i])
}
for-in loop through the array:
for value in values {
// It will give an error "canot assign to value:‘ value ’is a‘ let ’...
// value = "5"
print (value)
}
It should be noted that when using a for-in loop traversal, it is not allowed to assign a value to the loop constant, because the for-in loop implicitly declares the constant with let.
Modify array
Array provides append () method to add elements:
// Use var to define a variable array
var languages = ["Swift"]
// Add elements, the output is ["Swift", "Java"]
languages.append ("Java")
You can also use "+" to add an array:
// The output is ["Swift", "Java", "Ruby"]
languages = languages + ["Ruby"]
Array provides insert () method to add elements:
// Insert the element, then the first element of the array is "Go"
languages.insert ("Go", atIndex: 0)
Array supports the use of Range in "[]", so that multiple array elements can be obtained and assigned at once:
var languages = ["Swift", "OC", "PHP", "Perl", "Ruby", "Go"]
// Get the elements with index 1 ~ 4 in the array in languages
let subRange = languages [1 .. <4]
print (subRange) // output [OC, PHP, Perl]
// Replace the elements with index 2 ~ 4 in the array in languages with "C / C ++", "Python"
languages [2 ... 4] = ["C / C ++", "Python"]
print (languages) // Output [Swift, OC, C / C ++, Python, Go]
// Empty the array
languages [0 .. <languages.count] = []
print (languages) // output []
Array provides removeAtIndex (), removeLast () and removeAll () methods to delete:
var languages = ["Swift", "OC", "PHP", "Perl", "Ruby", "Go"]
// Delete the element with index 2, delete "PHP"
languages.removeAtIndex (2)
print (languages) // output [Swift, Perl, OC, Ruby, Go]
// Delete the last element, delete "Go"
languages.removeLast ()
print (languages) // output [Swift, Perl, OC, Ruby]
// delete all elements
languages.removeAll ()
print (languages) // output []
print (languages.count) // output 0
2. Dictionary
The dictionary is used to store data with a mapping relationship. Both the key and value can be data of any data type, and the key of the dictionary is not allowed to be repeated.
Declaration dictionary
There are two syntaxes for declaring a dictionary:
1. Use generic syntax, the format is: Dictionary
// Declare the dictionary using generic syntax
var dict: Dictionary <String, String>
// Declare the dictionary using simplified syntax
var scores: [String: Int]
Create a dictionary
There are also two ways to create a dictionary:
Use Dictionary's constructor
Use simplified syntax
// Create a Dictionary structure, using the default parameters
dict = Dictionary <String, String> ()
// minimumCapacity contains at least the number of key-value pairs, the default value is 2
scores = Dictionary <String, Int> (minimumCapacity: 5)
// Create a dictionary using simplified syntax
var health = ["Height": "178", "Weight": "75"]
Use a dictionary
The dictionary value needs to be followed by a square bracket "[]" after the dictionary variable. The square brackets are the key values corresponding to the dictionary value.
// Assign key value to height
var height = health ["身高"]
print (height) // Output Optional ("178")
// When accessing the value corresponding to a non-existent key, nil will be returned
var energy = health ["能量"]
print (energy) // output nil
As can be seen from the above code, when accessing the value corresponding to the dictionary according to the key value, the optional type containing the value value is returned, because the dictionary is not sure whether this key-value pair exists, and when the key-value pair exists, the key corresponding Value, otherwise it returns nil. At this time, we can solve this problem through forced analysis:
// The type of height is String ?, not String
var height: String? = health ["身高"]
if height! = nil
{
// Use! To perform forced parsing, the output is 178
print (height!)
}
The for-in loop can also be used to traverse the dictionary:
for heal in health
{
print (heal) // Output ("Height", 178) ("Weight", 75)
}
Dictionary key set and value set
If the program only needs to access the dictionary's key set and value set, it only needs to access the dictionary's keys attribute or values attribute.
var healths = ["Height": "178", "Weight": "75"]
var keys = Array (healths.keys)
var values = Array (healths.values)
print (keys) // output ["height", "weight"]
print (values) // Output ["178", "75"]
Modify dictionary
The dictionary provides the updataValue () method to modify the value of the dictionary. This method returns a Sting? Type value. If the key value exists, the modification is successful. If the key value does not exist, it returns nil. value
var healths = ["Height": "178", "Weight": "75"]
var result = healths.updateValue ("68", forKey: "weight")
print (result) // output Optional ("75")
print (health) // Output ["Height": "178", "Weight": "68"]
var result = healths.updateValue ("A", forKey: "blood type")
print (health) // Output ["blood type": "A", "height": "178", "weight": "68"]
The dictionary also provides the following methods to delete elements:
removeValueForKey: delete the value corresponding to the specified key
removeAll: clear the dictionary
var languages = ["Swift": 9000, "OC": 8600, "PHP": 3400,
"Perl": 4300, "Ruby": 5600, "Go": 5600]
// Delete the key-value pair whose key is "PHP"
languages.removeValueForKey ("PHP")
// Delete the key-value pair whose key is "Perl"
languages.removeValueForKey ("Perl")
// The following output: [Go: 5600, OC: 8600, Ruby: 5600, Swift: 9000]
print (languages)
print (languages.count) // output 4
You can also assign the value corresponding to Key to nil to delete the key-value pair:
// Delete the key-value pair whose key is "Go"
languages ["Go"] = nil
print (languages) // output [OC: 8600, Ruby: 5600, Swift: 9000]
// delete all elements
languages.removeAll ()
print (languages) // output [:]
print (languages.count) // output 0
Swift Quick Start (5) Collection