Collection types in Swift

Source: Internet
Author: User

A. Intro:

Swift was ranked 18th in the October 2014 Tiobe programming language rankings, and in less than half a year since the launch of the 2014WWDC release, Swift has been sought after by programmers who are no less enthusiastic than the hottest superstar Taylor Swift. In the near future, we believe Swift can develop smoothly and replace objective-c gradually.


Two. Collection types for Swift

The following regression topic. As an iOS developer, we are already familiar with common collection types such as Nsarray,nsdictionary,nsset, and their variable-like nsmutablearray,nsmutabledictionary, Nsmutableset. While Swift provides us with the native array and dictionary collection types, unfortunately, there is no set type such as set (which is expected to be added in the future). Unlike objective-c, Swift does not have a corresponding mutable type because a set type is mutable by the modifier var and let, so if a variable of a collection type is let, the collection type is immutable. If a variable of a collection type is var-decorated, then the collection type is mutable. For example:

var Mutablearray = array<int> () mutablearray.append (1) Let Immutablearray = Array<string> () Immutablearray.append ("item")    //compile-time error

If you don't know the difference between the modifier let and Var, you can simply understand that the Let modifier is a constant and cannot be changed once the value 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, which is that it must be an OC object (many times when we want to add a basic data type to it, we need to encapsulate it in nsnumber to put it in the collection). Swift, in contrast, claims to be type-safe, because Swift's features include the generic in modern languages. So when we call the initialization method of the collection type, we have to indicate the element data type of the collection type. Like what:

var intarray = array<int> () intarray.append intarray.append ("All")    //compile-time error var creditdictionary = Dictionary<string,int> () Creditdictionary.updatevalue (88888, Forkey: "Benson")


In the above example, an array of shapes is declared and a dictionary keytype to string,valuetype as Int. The shaping array can only hold the shape element, if the string element is placed, the compiler will error (it is worth noting that if you put a floating-point type or a Boolean type, the compiler will automatically convert it to shaping, such as 3.14 conversion to 3,true to 1). With generics, you can ensure type safety without the hassle of typing and forcing type conversions.

(There is no restriction on the element type of the array, but the dictionary sets the type limit for KeyType (type Constraints), which stipulates that KeyType must implement the Hashable protocol, which stipulates that the class must provide gettable HashValue properties.) Thankfully, string,int,double,bool and other common types have implemented the protocol, which is generally sufficient. )

Four. Shorthand form

For the initialization of a collection type, in most cases it is not used in the above example, but rather in a more concise form.

var shorthandarray = [Int] ()    //var intarray = array<int> () var shorthanddictionary = [String:int] ()    //var C Reditdictionary = dictionary<string,int> ()

As shown above, for an array type, you simply declare the type of the array in brackets, followed by a pair of parentheses (the parentheses can also have initialized parameters, such as [Int] (count:3,repeatedvalue:0)), for the dictionary type, Simply declare the type of key and value in parentheses, separated by a colon, followed by a pair of parentheses, in the same way that the parentheses can have parameters for the corresponding initialization method. Another scenario is that if a variable is known to be a collection type, it can be used in a simpler form if the value is assigned again:

Shorthandarray = []//Empty arrayshorthanddictionary = [:]   //Empty Dictionary

Because the type is known, you do not need to declare the appropriate type in brackets.


Five. Traversal of collection types

The most common operation for collection types is to iterate through the collection. These 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)}

In the example above, a for in loop is used to loop through each element in the print group. (Println is a swift built-in global function, similar to the Java System.out.println () method.) You can also see that the for loop is not surrounded by parentheses)

Output Result:

(This watermark: )


If you need to get the index value 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) ")}

Similar to traversing an array, except that each item that is traversed is a tuple (tuple) that contains two elements, one key and one value.


Six. Use Subscript (subscript)

Arrays array and dictionary dictionary can be added, deleted, and replaced using subscripts such as:

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 array operations, the subscript appears to be replaceable only, cannot add elements, and cannot delete elements (if an element is set to nil, the element type of the array must be set to optional).

The operation for the dictionary is quite complete and can be crud. It is important to note that when you get the value of a key in the dictionary by the subscript, the type returned is ValueType? (That is, the value type of the optional), you can use the optional binding or if and! Extract the value by using it, because the value may not exist in the dictionary and may be nil.


Seven. Simple initialization of collection types

It might be a leak, but the most important thing 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, and for arrays, because the elements in the array are string, the data type of the Countryarray is [string], in the same vein, The data type of festivaldic is [string:string].


Finally, it is important to emphasize that arrays and dictionary are different from OC's 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: (more specifically, arrays and dictionary are 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

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.