Swift Learning-strings & arrays & Dictionaries

Source: Internet
Author: User
Tags modifiers

String

    • Differences between the strings in OC and Swift
      • When the string type is nsstring in OC, the string type in Swift
      • The string @ "" In OC, the string "" in Swift
      • String in Swift is the first struct with higher performance
      • String supports direct traversal
      • Swift provides a seamless transition between string and NSString
Use of Strings
    • Use backslashes \ and parentheses () to interpolate the string (insert the constant \ variable into the string)
      • Let hand = 2
        var age1 = 20
        Let string1 = "I am (age1) year old, have \ (hand) only Hand"
      • You can also use string concatenation, but you must turn it into a string
        var string2 = "I this year" +string (age1) + "old, have \ (hand) only Hand"
    • Traversing strings
      • var string = "Hi Siri"
        For s in string.characters {//String.characters represents all the characters in a string
        Print (s)//printing 7 characters in sequence, space is also
        }
    • Concatenation of strings and other data types
      • Let name = "Siri"
        Let age = 10
        Let Siriinfo = "My name was \ (name), Age was \ (age)"
           My name is Siri, which is 10
    • Formatting time for string: 03:04
      • Let min = 3
        Let second = 4
        Let time = String (format: "%02d:%02d", arguments: [min, second])
    • Interception of strings
      • A special interception method is provided in Swift, but it is cumbersome and index is difficult to create
      • The simple way to do this is to turn the string into NSString to use. String-NSString After the identifier: as NSString
        • Let Baidu = "www.baidu.com"
          var subStr = (Baidu as NSString). Substringfromindex (4)//"baidu.com"
          SUBSTR = (Baidu as NSString). Substringtoindex (3)//"www"
          SUBSTR = (Baidu as NSString). Substringwithrange (Nsrange (Location:4, Length:5))//"Baidu"
    • Note: In swift, String has a method called ToInt that can convert a string to an int type. It is important to note that not all strings can be converted to integers.
      • Let Numstr = "123"
        Let number = Numstr.toint ()//It doesn't seem to work.
Array
    • Array: (array) is a set of ordered sets of elements of the same type, the immutable array when let is modified, the variable group when VAR is modified
      • Defines a mutable array that must be initialized to use
        var array1: [String] = [string] ()
        Define an immutable group
        Let array2: [nsobject] = ["WWL", 18]
    • Statement
      • Declaration method one: Var myarray1:array<string>
        Declaration method Two: Var myArrray2: [String]
    • Initialization
      • Initialize directly when defining
        var array3 = ["AAA", "SSS", "ddd"]//type derivation of string type
        Define first, then initialize
        var array4:array<string>
        Array4 = ["fff", "GGG", "HHH"]
Note: Arrays must be initialized to be used, and array types are specified at the time of declaration
    • Array operations:
      • Add data
        Array.append ("DD")
        Delete Element
        Array.removefirst ()
        modifying elements
        Array[0] = "ee"
        Take value
        ARRAY[1]
        inserting elements
        Array.insert ("TTT", atindex:0)
      • The array can also be used for interval
        ARRAY[1...2]
    • Traversal of an array
      • Normal traversal array
        For I in 0..<array.count {
        Print (Array[i])//with subscript
        }

        For in mode
        For item in array {
        Print (item)//no subscript required
        }

        Set the traversal interval
        For item in ARRAY[0..<2] {//0..<2 open interval 0,1 0...2 closed interval 0,1,2
        Print (item)
        }
    • Merging of arrays
      • Only arrays of the same type can be merged
        • var stringArr1 = ["AA", "BB", "CC"]
          var stringArr2 = ["dd", "EE"]
          var stringArr3 = array + array1;

          It is not recommended to store multiple types of data in an array
          var = [objectArr1, "AA"]
          var objectArr2 = ["BB", 44]
          OBJECTARR1 + OBJECTARR2
    • Checks whether the length of the array is 0 through a IsEmpty property that returns a Boolean type
      • var stringarr = ["AA", "BB", "CC"]

        If!stringarr.isempty {
        Print ("Stringarr has \ (stringarr.count) items")
        } else {
        Print ("Stringarr is Empty")
        }
        Stringarr has 3 items
    • Use the (+ =) operator to add an array to the end of another array
    • (+ =) operator to add an element to the end of the array as if it had been deleted
      • var stringarr = ["AA", "BB", "CC"]
        var stringArr1 = ["dd", "EE", "FF"]
        STRINGARR1 + = Stringarr
        Print (STRINGARR1)//["DD", "EE", "ff", "AA", "BB", "CC"]
    • 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
      • var Threestringarr = [String] (Count:3, Repeatedvalue: "HI")
        You can also not specify a type, thanks to type inference
        var Threedoublearr = Array (Count:3, repeatedvalue:2.0)
Dictionary
    • The dictionary type in Swift is dictionary, a generic collection. var modifiers are mutable dictionaries, let modifiers when mutable dictionaries
    • declaring Dictionary types:
      • var dict1:dictionary<int, string>
        var dict2: [Int:string]
    • Initialization
      • Must be initialized to use
      • var dict1:dictionary<int, string> = Dictionary ()
      • Define a mutable dictionary
        var dict3: [String:nsobject] = [String:nsobject] ()

        Initializing a dictionary while defining it
        Let dict4 = [' name ': ' Xiaosan ', ' age ': 18]//Type deduced [String:nsobject] Type

        Any object in swift, usually without the use of nsobject, using Anyobject
        var dict5:dictionary<string, anyobject>
        DICT5 = ["name": "DD", "age": 18]
    • Basic operation of the dictionary
      • Operation of the Dictionary
        var dict: [String:anyobject] = [String:anyobject] ()

        Dict = ["Age": +, "height": 1.74, "name": "Xiaocan"]

        Add data
        dict["weight"] = 60.0

        Delete data
        Dict.removevalueforkey ("Age")

        Modify Dictionary
        dict["name"] = "Xiaoer"
        Dict["Age"] = 18//If you do not have this key, add the data

        Inquire
        dict["Name"]
    • The traversal of a dictionary
      • Iterate through all the values in the dictionary
        For value in Dict.values {
        Print (value)
        }
        Iterate through all the keys in the dictionary
        For key in Dict.keys {
        Print (key)
        }

        Traverse all key-value pairs
        For (key, value) in Dict {
        Print (key)
        Print (value)
        }
    • Merging of dictionaries
      • var myDict1 = ["Name": "Xiaosan", "Age": 20]
        var myDict2 = ["Height": 1.77, "Address": "Taikang"]

        Dictionaries cannot be added and merged in different types and cannot be merged
        For (key, value) in MyDict1 {
        Mydict2[key] = value
        }
    • Removevalueforkey && Updatevalue (forkey:)
      • Dictionary of Updatevalue (forkey:) method to set or update a value for a particular key, set its value if the key does not exist, and update its value if the key exists, 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.
        • var dict = ["name": "Siri", "Age": "Address": "Nanjing"]

          Iflet OldValue = Dict.updatevalue ("Siri", Forkey: "name") {
          Print (OldValue)//Siri
          }

          Use the following banner to assign his value to nil to remove the key-value pair.
          Dict["Age" = Nil

          Print (DICT)//["Address": Nanjing, "name": Siri]
      • With the Removevalueforkey method, if there is a value corresponding to the key, a key-value pair is removed and the removed value is returned, otherwise nil is returned.
        • If Let Removedvalue = Dict.removevalueforkey ("address") {
          Print ("The Remove dict ' s adddress is \ (removedvalue)")//The Remove dict ' s adddress are Nanjing
          } else {
          Print ("The dict does not contain a value for address")
          }

Swift Learning-strings & arrays & Dictionaries

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.