Set Type in Swift, Swift set type

Source: Internet
Author: User

Set Type in Swift, Swift set type

I. Introduction:

In the Tianyi programming language ranking in 18th, Swift ranked. Since the first release of the WWDC press conference, swift has been sought after by programmers for less than half a year, he is no less enthusiastic than Taylor Swift, the Red Star. I believe that in the near future, swift will be able to develop smoothly and gradually replace Objective-C.


Ii. swift collection type

The following is a regression topic. As an iOS developer, we are very familiar with common collection types such as NSArray, NSDictionary, and NSSet, as well as their variable NSMutableArray, NSMutableDictionary, and NSMutableSet. Swift provides the native Array and Dictionary Collection types. Unfortunately, the Set type is not provided yet (it is expected to be added in the future ). Unlike Objective-C, swift does not have the corresponding mutable type because whether a set type is variable is determined by the modifier var AND let. Therefore, if a set type variable is modified by let, the set type is unchangeable. If a set type variable is modified by var, the set type is variable. For example:

Var mutableArray = Array <Int> () mutableArray. append (1) let immutableArray = Array <String> () immutableArray. append ("item") // compilation Error

If you do not know the difference between the modifier let and var, you can simply understand that the variable modified by let is a constant and cannot be changed once the value is assigned. The value of the variable modified by var can be dynamically changed.


Iii. Fan type set

The set type of Objective-C has only one requirement on the elements in the set, that is, it must be an OC object (many times when we want to add a basic data type to it, you must encapsulate NSNumber to put it in the set ). Swift, however, is different. swift claims to be type-safe, because its features include the general model (generic) that is available in modern languages ). Therefore, when calling the initialization method of the set type, we must specify the Element Data Type of the set type. For example:

Var intArray = Array <Int> () intArray. append (2014) intArray. append ("2014") // compile-time error var creditDictionary = Dictionary <String, Int> () creditDictionary. updateValue (88888, forKey: "Benson ")


In the preceding example, an integer array and a dictionary whose KeyType is String and ValueType is Int are declared. The integer array can only store integer elements. If an integer element is put into a string, the compiler reports an error (it is worth noting that if it is put into a floating point or boolean type, the compiler automatically converts it to an integer type, for example, 3.14 is converted to 3, and true is converted to 1 ). With the model, you can ensure the type security, without having to perform complicated operations such as type judgment and forced type conversion.

(There are no restrictions on the element types of arrays, but the dictionary sets the Type Constraints for the KeyType. It specifies that the KeyType must implement the Hashable protocol, this Protocol requires that the class must provide the hashValue attribute of gettable. Fortunately, common types such as String, Int, Double, and Bool all implement this protocol, which is generally enough .)

Iv. Abbreviations

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

var shorthandArray = [Int]()    // var intArray = Array<Int>()var shorthandDictionary = [String:Int]()    // var creditDictionary = Dictionary<String,Int>()

As shown above, for the array type, you only need to declare the array type in brackets, followed by a pair of parentheses (the parentheses can also contain initialization parameters, such as [Int] (count: 3, repeatedValue: 0). For the dictionary type, you only need to declare the key and value types in brackets and separate them with colons. Then, you can use a pair of parentheses. Similarly, parameters of the initialization method can also be included in parentheses. In another case, if a variable is known to be of the set type, a simpler form can be used to assign values again:

shorthandArray = [] // empty arrayshorthandDictionary = [:]   // empty dictionary

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


5. traversal of set types

The most common operation of the set type is to traverse the set. The following lists the arrays and dictionaries:

var carArray = [String]()carArray.append("Mercedes-Benz")carArray.append("Toyota")carArray.append("Porsche")for car in carArray {    println(car)}

The preceding example uses a for in loop to print each element in the array cyclically. (Println is a global function built in swift, similar to the java System. out. println () method. In addition, we can see that the for loop does not need to be surrounded by parentheses)

Output result:

(This watermark ..)


If you need to obtain the index value during the loop process, you can use the global function enumerate in the swift Standard Library:

for (index,value) in enumerate(carArray) {    println("index\(index):\(value)")}

Print result:

index0:Mercedes-Benzindex1:Toyotaindex2:Porsche

Next we will 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) has \(legs)leg(s)")}

Similar to traversing an array, each item is a tuple, which contains two elements: key and value.


6. subscript)

Array and Dictionary can be added, deleted, or replaced as the following objects, for example:

Var carArray = [String] () carArray. append ("Mercedes-Benz") carArray. append ("Toyota") carArray. append ("Porsche") carArray [0] = "BMW" // Mercedes-Benz is replaced with 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 element value if let legs = animalLegs ["kangaroo"] {println ("kangaroo has \ (legs) legs ")} else {println (" not defined ")}

For Array Operations, the subscript can only be replaced. You cannot add or delete elements. (If you set an element to nil, you must set the element type of the array to optional ).

You can perform CRUD operations on the dictionary. Note that when you obtain the value of a dictionary key through subscript, the returned type is ValueType? (Value Type of optional), you can use optional binding or if and! Extract this value because the value may not exist in the dictionary, and thus it may be nil.


7. Simple initialization of set types

It may be omitted, but it is also the most important point, that is, how to assign values to variables by using the array and dictionary literal (literal.

var countryArray = ["China","Japan","Russia","India","Canada"]var festivalDic = ["National's Day":"10-01","Christmas Day":"12-25","New Year":"01-01"]

The literal value of an array is generally in the form of [value, value, value...], the general form of the dictionary is [key: value,...]. The Data Types of arrays and dictionaries are derived from type inferrence. For arrays, The countryArray data type is [String] Because all elements in the array are strings. similarly, the festivalDic data type is [String: String].


It should be emphasized that Array and Dictionary are different from NSArray and NSDictionary of OC. Array and Dictionary are value types rather than reference types. Therefore, the original values of Array and Dictionary are not affected because the original values of Array and Dictionary are of the struct type .)

var original = [1,2,3]var steal = originalsteal.append(4)original.count // 3steal.count    // 4



What are the JAVA Collection types?

The Collection classes used in Java APIs all implement the Collection interface. Their class inheritance structure is as follows:

Collection <-- List <-- Vector

Collection <-- List <-- ArrayList

Collection <-- List <-- items List

Collection <-- Set <-- HashSet

Collection <-- Set <-- HashSet <-- revoke HashSet

Collection <-- Set <-- SortedSet <-- TreeSet

Vector: Array-based List encapsulates some functions not available in Array for our convenience, and it cannot be restricted by Array. Performance is impossible

Beyond Array. Therefore, when possible, we need to use Array more. Another important point is that the Vector "sychronized", which is also

The only difference between ArrayList.

ArrayList: Like a Vector, it is an Array-based linked list, but the difference is that ArrayList is not synchronized. Therefore, the performance is better than that of Vector,

When running in a multi-threaded environment, you need to manage the synchronization of threads on your own.

Sort List: the sort List is different from the previous two lists. It is not based on Array, so it is not limited by Array Performance. Each Node contains two parties.

Content: 1. data of the node itself; 2. Information of the next node (nextNode ). Therefore, when you add a consumer list, you do not need to delete it like

Like Array-based List, a large amount of data must be moved. You only need to change the relevant information of nextNode. This is the advantage of listing.

List summary:

1. All lists can only contain tables composed of a single object of different types, rather than Key-Value pairs. Example: [tom, 1, c];

2. All lists can have the same elements. For example, the Vector can have [tom, koo, too, koo];

3. All lists can have null elements, such as [tom, null, 1];

4. Array-based List (Vector, ArrayList) is suitable for queries, while sorted List (linked List) is suitable for adding and deleting operations.

HashSet: Although Set and List all implement the Collection interface, their implementation methods are quite different. List is basically based on Array. But Set is

Implemented based on HashMap. This is the fundamental difference between Set and List. The HashSet storage method uses the Key in HashMap as the corresponding storage item of the Set.

Whether the set in c # belongs to the reference type or value type

Reference Type

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.