Swift Collection Types

Source: Internet
Author: User

Introduction to Swift collection types

Like OC, Swift also offers three types of collections: Array, set, and dictionary. Arrays is used to store data sequentially, sets is used to store different values in an unordered order, dictionaries is used to store unordered key-value pairs.

However, Swift's collections and OC collections are different in the element type requirements to be stored.

Swift collections explicitly the element type. In OC, collections (for example, array, dictionary, set) has only one requirement for the type of stored elements: it is a class instance, but in swift, the type of elements stored in collections must be clear, This means that we cannot insert incorrect data types into collections, but on the other hand, this ensures that we can be very confident about the type of data that is obtained. Swift's use of explicit type collections ensures that our code is very clear about the types of work required, and that we can discover any type mismatch errors during the development phase.

Swift collections can be used to store value type data. As mentioned above, in OC, the element in collections must be a class instance, not a basic data type or enumeration such as int, which is not true for Swift. Swift's collections is not picky about element types, but can be either value types or reference types. (But the same collection element type must be the same).

Mutable and immutable

In OC, each type of collection corresponds to immutable and mutable versions, such as dictionary-type nsdictionary and nsmutabledictionary.

In Swift, the mutablility nature of collection is determined by the keyword var and let , if the collection object is defined with var adornments, then the collection type object is mutable, This means that you can apply additions and deletions to the collection object, and conversely, if you define a collection object with let adornments, then the collection type object is immutable. means that the contents and size of the collection cannot be changed;

P.S: It can also be seen that Swift is let var much more powerful than the C language const , and therefore cannot be var let likened to a simple analogy const .

Array Defining Arrays

Array construction statements are written in two ways: Array<SomeType> or [SomeType] , as follows:

var shoppinglist: [String] = ["Eggs", "Milk"]var mygirlfriends:array<string> = ["Lily", "Lucy"]
create an empty array

In OC, there are several ways to create an empty array: [[NSMutableArray alloc] init] or [NSMutableArray array] .

Declare and initialize var Ints = [Int] ()//First declare after initialize VAR Strings: [string]strings = []//equivalent to Strings = [String] ()
Accessing and modifying arrays

The operations supported by arrays in OC are also supported in Swift, but many methods have different names.

Determine if the array is empty

In OC, the practice of judging whether an array is empty is to access its Count property, which in Swift isEmpty provides a more convenient way.

inserting elements

For example, adding elements to the OC in the use of the method addObject: , in Swift, in append addition append to the method, Swift also provides the += operation (the += Syntax sugar bar), it is used to add an n elements. As follows:

var mygirlfriends = [String] () mygirlfriends.append ("Zhang Yi Ya") mygirlfriends.append ("Licuihua") mygirlfriends + = ["Wang Xiaoli", "Chen Mi"]

appendand += both add elements at the end of the array, and if inserted at the specified index, the method is used insert .

Sub-array operations

There are operating interfaces for sub-arrays in OC, for example subarrayWithRange: , providing easier access in Swift-using ... and ..< operators, such as myGirlFriends[1..<3] accessing index=1,2 elements and myGirlFriends[1...3] accessing index=1,2,3 elements.

Dictionary

In OC, the dictionary requires both key and value to be instances, so in general, the key value is the NSString type (although other types of objects can also be used as key values). In Swift, because there is no such requirement, the key and value values can be any type of data, but, as with arrays, consistency must be guaranteed, i.e. keys and values that can be stored in a particular dictionary must be clearly defined in advance.

Note: The only requirement for the dictionary to key type is:

A dictionary Key type must is conform to be Hashable protocol.
Make sure the keytype is hashed so that it is unique and easy to hash! All Swift basic types (such as string/int/double) are hashed by default and can be used as key type.

Defining Dictionaries

In OC, the corresponding symbol for the array is [] that the dictionary corresponds to the symbol, {} but in Swift, as well as arrays, the dictionary corresponds to the symbol [] .

There are also two types of dictionary declarations: Dictionary<KeyType, ValueType> or [KeyType: ValueType] .

Create an empty dictionary
Declare and initialize var nameofintegers = [int:string] ()//Declare first, then initialize Var httpstatusmessage:dictionary<int, string> Httpstatusmessage = [:]//equivalent to httpstatusmessage = [int:string] ()
Dictionary literals

The dictionary literals in Swift are similar to the dictionary literals in OC, Key-value are all using key: value structures, and Key-value are , separated. But there are two different points: first, the former is used, the latter is used, and the latter is used [] , {} @ as follows:

var families = ["Father": "Sad Jason", "Son": "Zhang Buhuai"]
Access Key-value

The so-called "access Key-value" is nothing more than reading a value,swift by Key. So far, only one way has been defined: through subscript access, such as families["Father"] .

    • The key type of subscript must be the same as the key typed by the dictionary at the time of definition, otherwise an error is given;
    • The return value of value that accesses dictionary through subscript is a optional,optional that contains a valid value or nil;
Modify Key-value

"Modify Key-value" refers to adding a key-value to dictionary or changing key-value. Swift has so far provided two ways: based on subscript and update methods, as follows:

var families = ["Father": "Sad Jason", "Son": "Zhang Buhuai"]families.updatevalue ("Liu", Forkey: "Mother")//equivalent to families[ "Mother"] = "Liu"

Obviously, families["Mother"] = "Liu" there are two kinds of results:

    • familiesThe Key-value of key is not present in the dictionary "Mother" , and the result of processing is a families pair of key-value "Mother": "Liu" ;
    • There is a Key-value key in the dictionary, and the result is the value of the families "Mother" families "Mother" key value pair in key "Liu" .

updateValue(forKey:)Slightly different from subscript, it returns a optional that contains the dictionary value type whose value is the value before the Key-value update.

Remove Key-value

"Remove Key-value" refers to deleting a key-value that may exist in dictionary. As with "Modify Key-value", Swift provides two ways to "Remove Key-value": dictionary[key] = nil or dictionary. removeValueForKey(key) , as follows:

Families.removevalueforkey ("Father") families["Son" = Nil

The difference is that it removeValueForKey returns a optional that may contain the value of the key value pair of the remove, or nil;

Traverse Dictionary

The traversal of dictionary in Swift is much more elegant than OC, in a way similar to Python, as follows:

var families = ["Father": "Sad Jason", "Son": "Zhang Buhuai"]for (member, name) in families {    println ("\ (member): \ (NA Me)}
Summary

Swift has a much more elegant operation for collection than OC, such as traversing a dictionary, using ..< an Access sub-array, providing a IsEmpty property to determine whether the collection is empty, and so on. But the individual is not very fond ... of this operator, try to use less.

Swift Collection Types

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.