Swift learns three

Source: Internet
Author: User

http://blog.csdn.net/kuloveyouwei/article/details/36005299

Swift provides two collection types to store collections, arrays, and dictionaries. An array is a collection of serialized lists of the same type. A dictionary is a non-serialized collection that can use a unique identifier similar to a key to get a value. In Swift, both the key and the value of the array and dictionary must be explicit about its type. This means that the array and the dictionary do not insert a value of the wrong type, resulting in an error. This also means that when you retrieve a value in an array and a dictionary, you can determine its type. Swift uses the identified collection types to ensure that the code works without errors, and allows you to catch errors earlier in the development phase.

1. Arrays

The swift array is a stored determined value, and the Nsarray and Nsmutablearray classes in this objective-c are distinguished. Because they are stored in various objects, and do not provide specific information to return any relevant objects. In Swift, whether it is a deterministic declaration or an implicit declaration, the array is very certain what type it is stored on itself, and it does not necessarily require that the class object be stored. So the swift array is type-safe because it always determines the values it can contain.

[OBJC]View Plaincopy
  1. Initializing an array
  2. Let array1:string[]=["A","B"];
  3. An array is defined as a variable (using the var identifier) instead of a constant (using the Let identifier)
  4. var array2:string[]=["AA","BB"];
  5. Initialize an empty array
  6. var array3=string[] ();
  7. The SWIFT array type also provides an initialization method to create an array that determines the length and provides a default value. You can add a new array by this initialization method, the number of elements becomes count, and the appropriate default value is Repeatedvalue
  8. var array4=int[] (count:3,repeatedvalue:0);
  9. Array2 variable array, you can add elements
  10. Array2. Append ("cc");
  11. You can also add elements by using the + = operator
  12. array2+= "CC";
  13. println (array2);
  14. /*
  15. * Print Results
  16. *[AA, BB, CC]
  17. */
  18. Index value by subscript method
  19. var yuansu1=array2[0];
  20. println (Yuansu1);
  21. /*
  22. * Print Results
  23. *aa
  24. */
  25. You can also modify the values in a range
  26. Array2[1 ...  2]=["ee","FF"];
  27. println (array2);
  28. /*
  29. * Print Results
  30. *[AA, EE, FF]
  31. */
  32. Inserting an element at a location in an array
  33. Array2. Insert ("oo", Atindex:0);
  34. println (array2);
  35. /*
  36. * Print Results
  37. *[OO,AA, EE, FF]
  38. */
  39. Delete an element at a location
  40. Array2. Removeatindex (0);
  41. println (array2);
  42. /*
  43. * Print Results
  44. *[AA, EE, FF]
  45. */
  46. Move the last element of the divisor group
  47. var lastyuansu=array2. Removelast ();
  48. Iterating through an array
  49. For item in array2
  50. {
  51. println (item);
  52. }

2. Dictionaries

The Swift dictionary stores a type of specific keys and values, and the Objective-c nsdictionary and nsmutabledictionary are distinguished by certain differences, because they are used by various objects as their keys and values, And does not provide any specific information about the object. In Swift, for a particular dictionary, the keys and values that it can store are deterministic, either explicitly declared or implicitly inferred types. Swift's dictionary notation is that Dictionary<keytype,valuetype>,keytype is the key you want to store, and ValueType is the value you want to store. The only limitation is that KeyType must be hashed (hashable)--that is, providing a form that allows them to be independently identified. All of Swift's underlying types (such as String, shape (Int), double-precision (double) and Boolean (BOOL)) are hashed by default (hashable), and these types are often used as keys to the dictionary. Enumeration member values do not require a assistance value (associated values) (specifically described in enumerations) as well because they are also hashed (hashable) by default.

[OBJC]View Plaincopy
  1. Initialize a dictionary
  2. Let dict1:dictionary<string,string>=[' Name ':' Yu ',' age ':' 26 '];
  3. As with arrays, if you initialize a dictionary with the same type, you can not specify the type of dictionary.
  4. var dict2:dictionary<string,string>=["Name2":"Yu","Age2":"26"];
  5. Create an empty Dictionary
  6. var dict3=dictionary<string,string> ();
  7. Subscript method, when there is no this key, is a new element
  8. Dict2["Sex"]="Nan";
  9. /*
  10. * Print Results
  11. *[name2:yu, age2:26, Sex:nan]
  12. */
  13. Modify
  14. Dict2["Sex"]="n";
  15. println (dict2);
  16. /*
  17. * Print Results
  18. *[name2:yu, age2:26, Sex:n]
  19. */
  20. Similarly, use the dictionary updatevalue (forkey:) method to set or update the value of a particular key. As with the subscript example above, Updatevalue (Forkey:) method sets its value if the key does not exist, updates its value if the key exists, and Updatevalue (Forkey:). method if it is updated, the original old value is returned rthis enables you can use this to determine if an update has occurred.
  21. If let OldValue = Dict2. Updatevalue ("Wang", forkey: "Name2")
  22. {
  23. println (dict2);
  24. }
  25. /*
  26. * Print Results
  27. *[name2:wang, age2:26, Sex:n]
  28. */
  29. The value is obtained by subscript method
  30. If let value = Dict2["Age2"]
  31. {
  32. println (value);
  33. } Else
  34. {
  35. println ("no Exsit")
  36. }
  37. You can use the following banner to assign his value to nil to remove the key value pair.
  38. Dict2["Sex"]=Nil;
  39. println (dict2);
  40. /*
  41. * Print Results
  42. *[name2:yu, age2:26]
  43. */
  44. Similarly, removing a key-value pair from a dictionary can use the Removevalueforkey method, which, if there is a value corresponding to the key, removes a key-value pair and returns the removed value, otherwise nil.
  45. If let Removedvalue = Dict2. Removevalueforkey ("Age2")
  46. {
  47. println (dict2);
  48. } Else
  49. {
  50. println (dict2);
  51. }
  52. Traverse Dictionary
  53. for (Key,value) in Dict2
  54. {
  55. println ("\ (key): \ (value)");
  56. }

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Swift learns three

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.