A. Intro:
In the October 2014 Tiobe programming language rankings, Swift ranked 18th place. Less than half a year since the launch of the 2014WWDC conference, Swift has been sought after by programmers who are no less enthusiastic than the hottest superstar Taylor Swift. Believe in the near future. Swift can evolve smoothly. and gradually replace the objective-c.
Two. Collection types for Swift
The following regression topics. As an iOS developer. We are already familiar with common collection types such as Nsarray,nsdictionary,nsset. And their variable homogeneous nsmutablearray,nsmutabledictionary,nsmutableset. And Swift provides us with the native array and dictionary collection types, unfortunately. There is no set type available at the moment (estimated to be added in the future).
Unlike Objective-c, there is no corresponding mutable type for swift. The reason is whether a collection type is mutable by the modifier var and let. So. Suppose a variable of a collection type is let-decorated. Then this collection type is immutable. If a variable of a collection type is var-modified, the collection type is mutable.
Like what:
var Mutablearray = array<int> () mutablearray.append (1) Let Immutablearray = Array<string> () Immutablearray.append ("item") //compile-time error
Suppose you don't know the difference between a modifier let and a Var, it's easy to understand. A let modifier is a constant and cannot be changed once it is assigned. The value of variables modified by Var can be changed dynamically.
Three. Model Collection
The Objective-c collection type has only one requirement for the elements in the collection. That is, it must be an OC object (very often when we want to add a basic data type to it.) Have to use the NSNumber encapsulation talent put in the collection to go to). And Swift is different. Swift claims to be type-safe, as Swift's features include the generic paradigm in modern languages (generic). So when we call the initialization method of the collection type, we have to indicate the element data type of the collection type.
Example:
var intarray = array<int> () intarray.append intarray.append ("All") //compile-time error var creditdictionary = Dictionary<string,int> () Creditdictionary.updatevalue (88888, Forkey: "Benson")
In the example above, an array of shapes is declared and a dictionary keytype to string,valuetype as Int.
The shaping array can only hold the shaping elements. Assuming that a string element is placed, the compiler will give an error (it is worth noting that, assuming that it is placed in a floating-point type or Boolean type, the compiler will voluntarily convert it to shaping, for example 3.14 to 3.) True to convert to 1). With generics, you can ensure type safety without the hassle of type inference and coercion of type conversions.
(the element type of the array has no restrictions whatsoever.) The dictionary, however, sets the type limit for KeyType (type Constraints). It stipulates that KeyType must implement the Hashable protocol, which stipulates that the class must provide gettable HashValue attributes. Fortunately, String,int,double,bool and other frequently used types have implemented the protocol, which is generally sufficient. )
Four. Shorthand form
For the initialization of a collection type, in most cases the notation in the example above is not used. But in a more concise form.
var shorthandarray = [Int] () //var intarray = array<int> () var shorthanddictionary = [String:int] () //var C Reditdictionary = dictionary<string,int> ()
As you can see above, for an array type, you simply declare the type of the array in brackets. Then a pair of parentheses can be followed (the parentheses can also have initialization parameters, for example [Int] (count:3,repeatedvalue:0)). For dictionary types, only the type of key and value is declared in parentheses, separated by a colon, followed by a pair of parentheses, in the same vein. Parentheses can also have parameters corresponding to the initialization method. The second scenario is that if a variable is known to be a collection type, then it can be used in a simpler form when the value is assigned again:
Shorthandarray = []//Empty arrayshorthanddictionary = [:] //Empty Dictionary
Because the type is known, it is not necessary to declare the corresponding type in brackets.
Five. Traversal of collection types
The most common use of collection types is to iterate through the collection. The following are traversed for arrays and dictionaries, respectively:
var cararray = [String] () cararray.append ("Mercedes-benz") cararray.append ("Toyota") cararray.append ("Porsche") for Car in Cararray { println (CAR)}
The example above uses a for in loop. Loop through each element in the print group. (Println is a built-in global function for Swift.) A System.out.println () method similar to Java.
Additionally, you can see that the for loop is not surrounded by parentheses)
Output Result:
(This watermark.)
。
)
Assuming that the index value needs to be obtained during the loop, you can use the global function enumerate in the SWIFT standard library:
for (Index,value) in enumerate (Cararray) { println ("index\ (index): \ (Value)")}
Printing results:
Index0:mercedes-benzindex1:toyotaindex2:porsche
The next step is to traverse the dictionary:
var animallegs = [String:int] () Animallegs.updatevalue (4, Forkey: "Deer") animallegs.updatevalue (8, Forkey: "Crab") Animallegs.updatevalue (2, Forkey: "Kangaroo") for (Animal,legs) in Animallegs { println ("\ (animal) have \ (legs) Leg (s) ")}
Like traversing an array, just iterating through each item is a tuple (tuple). The tuple consists of two elements, one is key, and the other is value.
Six. Use Subscript (subscript)
Arrays array and dictionary dictionary can be used in the form of subscripts, deletions and substitutions, for example:
var cararray = [String] () cararray.append ("Mercedes-benz") cararray.append ("Toyota") cararray.append ("Porsche") Cararray[0] = "BMW" //Mercedes is replaced by BMW [Replace operation]var animallegs = [String:int] () Animallegs.updatevalue (4, Forkey: "Deer" ) Animallegs.updatevalue (8, Forkey: "Crab") animallegs.updatevalue (2, Forkey: "Kangaroo") animallegs["sheep"] = 4 / /Add an element animallegs["deer"] = nil //delete an element animallegs["crab"] = 6 //Replace the value of the element if let legs = animallegs["Kangaroo"] {
println ("Kangaroo have \ (legs) legs")} else { println ("Not Defined")}
For an array operation, the subscript seems to be able to replace only, cannot add elements, and cannot delete elements (assuming that an element is set to nil, the element type of the array must be set to optional).
The operation for dictionaries is more complete and can be crud. It is important to note that you get the value of a key in the dictionary by using the subscript. What type of Return is ValueType? (That is, the value type of optional). Can be used optional binding or if and! Use to extract the value. Because the value may not exist in the dictionary, it may be nil.
Seven. Simple initialization of collection types
It might be a leak, but it's also the most important point. is how to use arrays and dictionary literals (literal) to assign values to variables.
var countryarray = ["China", "Japan", "Russia", "India", "Canada"]var festivaldic = ["National's Day": "10-01", "Christmas Day ":" 12-25 "," New Year ":" 01-01 "]
The general form of an array literal is [value,value,value ...], the general form of the dictionary is [Key:value,key:value,key:value,...]. The data types of arrays and dictionaries are derived from type inferrence, for arrays, because the elements in the array are string, so the data type of the Countryarray is [string], the same as The data type of festivaldic is [string:string].
Finally, it is important to emphasize that arrays and dictionary are different from OC Nsarray and Nsdictionary. Array and dictionary are value types (value type), not reference types. So. The array and dictionary values are generally copy, and their original values are not affected: (in more detail.) Arrays and dictionary are both struct types, and string is no exception. )
var original = [1,2,3]var steal = Originalsteal.append (4) original.count//3steal.count //4
Collection types in Swift