- Array (Arrays)
- Dictionary (Dictionaries)
Array (Arrays)
In OC, Nsarray and Nsmutablearray these two classes can store objects of any type and do not provide any special information about the returned object.
In swift, the type must be explicit before the data value is stored in an array. A method is an explicit type callout or type inference, and it is not required to be a class
type.
//定义了一个存储 字符串类型 的可变数组(‘var‘字段修饰)var shoppingList: [String] = ["Eggs", "Milk"]//定义了一个存储 字符串类型 的不可变数组(‘let‘字段修饰)let peopleList: [String] = ["Danny", "Mike", "Johnnie"]
Note:
Of course you can omit the type annotation, because Swift can infer the correct type based on your content, such as the following code.
var shoppingList = ["Eggs", "Milk"]
Creating and constructing arrays
//创建一个整型空数组var array1 = [Int]()//创建一个特定大小,并且所有数据都为默认的整型数组var array2 = [Int](count: 3, repeatedValue:1)//创建一个特定大小,并且数据类型为默认的推断为浮点型的数组var array3 = [](count: 3, repeatedValue:2.5)
Array additions and deletions
-
Add (Insert data)
There are several ways to insert data into an array in swift:
1) append ()
method
shoppinglist. append ( "flour")
2) Insert (Atindex:)
method
shoppinglist.insert ( "Maple syrup", atindex: 0)
3) + =
assignment operator
shoppinglist + = [ "baking Powder"]
-
Delete (remove data)
Removes the data item at the specified location with the Removeatindex ()
method. This method removes the data item stored in the array at a particular index value and returns the removed item (the returned data item can be ignored if not used):
let maplesyrup = Shoppinglist.removeatindex (0)
To remove the last item of data by using the Removelast ()
method
let apples = Shoppinglist.removelast ()
-
Change (update data)
// Update a data item by specifying an item Shoppinglist[0] = "Six eggs" //update the interval data item Shoppinglist[4.. "Bananas", "Apples"]
Note:
We cannot add new items at the end of the array by using the following banner. If we try to retrieve data from an index that is out of bounds or set new values in this way, we will throw a run-time error. We can use the index value and the Count property of the array to compare to verify the validity of an index before using it. The maximum index value is always count-1
, except when count
equals 0 o'clock (indicating that this is an empty array), because the array is 0 index
Check (Access data)
//获取第0项数据并赋值给变量firstItemvar firstItem = shoppingList[0]//获取某个区间的数据项并赋值给另外一个数值let tempArr = shoppingList[1...2]
Traversal of an array
for-in
iterate through the data items in the array:
"Way One"
let array = ["Danny", "Johnnie", "Mike"]//遍历数组数据项for item in array { print(item)}
控制台打印:DannyJohnnieMike
"Way Two"
let array = [ " Danny ", " Johnnie ", " Mike "]// Traversing array data items for (idx, value) in array. Enumerate () {print ( "Idx:\ (IDX) Value:\ (value)}
控制台打印:idx:0 value:Dannyidx:1 value:Johnnieidx:2 value:Mike
Dictionary (dictionaries) to create dictionary literals
In OC, the format of the dictionary literal is: @{@"key" : @"value"}
, while Swift inside, the dictionary literal and the array literal are enclosed in brackets []
. The format is:[key 1: value 1, key 2: value 2, key 3: value 3]
//创建一个var airports: [String:String] = ["TYO": "Tokyo", "DUB": "Dublin"]
//创建一个键为String,值为Int的空字典var dic1 = Dictionary<String, Int>()
Search and delete of dictionaries
Add (Insert data)
Use the subscript syntax in the dictionary to add new data items. You can use an appropriate type of key as the subscript index and assign a new value of the appropriate type:
airports["LHR"] = "London"
-
Delete (remove data)
Removes a key-value pair from the dictionary by using the Removevalueforkey ()
method. This method removes the key-value pair when the key-value pair exists and returns the removed value or returns nil
without a value:
//remove the corresponding value by the key value "DUB" let removedvalue = Airports.removevalueforkey ( "DUB")
-
Change (update data)
Changes the value of a specific key by using subscript syntax:
// Use subscript syntax to change the value corresponding to a specific key Airports[ "LHR"] = "London Heathrow"
can also set or update the value corresponding to a specific key through the Updatevalue (forkey:)
method. This method also returns the original value before the update value or nil
, which allows us to check whether the update was successful:
//to update the old value with the "DUB" key "Dublin internation" let oldValue = Airports.updatevalue ( " Dublin internation ", forkey: " DUB ")
Check (Access data)
Use the subscript syntax to retrieve the value for a specific key in the dictionary. Because it is possible to use a key that has no value, the optional type returns the relevant value that exists for the key, otherwise it returns nil
:
if let airportName = airports["DUB"] { print("DUB键对应的值为: \(airportName).")} else { print("DUB键没有对应的值")}
控制台打印:DUB键对应的值为: Dublin Internation.
The traversal of a dictionary
"Way One"
Iterate through for-in
a key-value pair in a dictionary. The data items in each dictionary are returned by the (key, value) tuple, and we can use temporary constants or variables to decompose these tuples:
//遍历字典对应的键值对for (key, value) in airports { print("\(key): \(value)")}
控制台打印:TYO: TokyoLHR: London Heathrow
"Way Two"
We can also keys
values
retrieve all the keys and values of a dictionary by accessing its or properties:
//遍历字典所有键for key in airports.keys { print("该字典的键:\(key)")}//遍历字典所有值for value in airports.values { print("该字典的值:\(value)")}
控制台打印:该字典的键:LHR该字典的键:TYO该字典的值:London Heathrow该字典的值:Tokyo
Note:
When you want to save the keys and values of the dictionary, you can use the array's API Array()
to store them.
//将字典的所有键存进keys数组中let keys = Array(airports.keys)//将字典的所有值存进values数组中let values = Array(airports.values)
Swift into the Pit series-collection type