Initialising empty arrays of dictionaries in Swift

后端 未结 6 1230
北恋
北恋 2021-01-30 02:18

I\'m trying to wrap my head around initialising empty arrays in Swift.

For an array of strings it\'s pretty straight forward :

var myStringArray: String         


        
相关标签:
6条回答
  • 2021-01-30 02:30

    You can no longer use element concatenation.

    class Image {}
    Image i1
    Image i2
    
    var x = [Image]()
    
    x += i1 // will not work (adding an element is ambiguous)
    x += [i1] // this will work (concatenate an array to an array with the same elements)
    
    x += [i1, i2] // also good
    
    0 讨论(0)
  • 2021-01-30 02:36

    You can use this if u want to use swift 2.3!

    let path = "/Library/Application Support/Apple/iChat Icons/Flags/"
    let image1 = UIImage(contentsOfFile: readPath + "Brazil.png")
    let image2 = UIImage(contentsOfFile: readPath + "Chile.png")
    
    var myImageArray = [UIImage]()
    myImageArray.append(image1)
    myImageArray.append(image2)
    
    0 讨论(0)
  • 2021-01-30 02:38

    The reason this isn't working:

    var myNewDictArray: Dictionary[] = []
    

    is that you need to provide types for the keys and values of a dictionary when you define it. Each of these lines will create you an empty array of dictionaries with string keys and string values:

    var dictArray1: Dictionary<String, String>[] = Dictionary<String, String>[]()
    var dictArray2: Dictionary<String, String>[] = []
    var dictArray3 = Dictionary<String, String>[]()
    
    0 讨论(0)
  • 2021-01-30 02:42

    This will create an empty, immutable dictionary:

    let dictionary = [ : ]

    And if you want a mutable one:

    var dictionary = [ : ]

    Both of these dictionaries default to Dictionary<String?, AnyObject?>.

    0 讨论(0)
  • 2021-01-30 02:52
    var yourArrayname = [String]() // String or anyOther according to need
    
    0 讨论(0)
  • 2021-01-30 02:54

    You need to give types to the dictionaries:

    var myNewDictArray: [Dictionary<String, Int>] = []
    

    or

    var myNewDictArray = [Dictionary<String, Int>]()
    

    Edit: You can also use the shorter syntax:

    var myNewDictArray: [[String:Int]] = []
    

    or

    var myNewDictArray = [[String:Int]]()
    
    0 讨论(0)
提交回复
热议问题