Swift: dictionaries inside array

前端 未结 4 856
半阙折子戏
半阙折子戏 2021-01-16 04:08

Data:

[
    { firstName: \"Foo\", lastName: \"Bar\" },
    { firstName: \"John\", lastName: \"Doe\" }
]

How can I have this kind of structu

4条回答
  •  梦毁少年i
    2021-01-16 04:26

    Are you sure you really want a dictionary within an array? The code you've given indicates more an array with named columns, which can be achieved using something like the following:

    struct Name {
        var firstName : String
        var lastName : String
    }
    
    var persons1 : Array =  [
        Name(firstName: "Foo", lastName: "Bar"),
        Name(firstName: "John", lastName: "Doe")
    ]
    persons1[0].firstName       // "Foo"
    
    var persons2 : Array<(firstName: String, lastName:String)> = [
        (firstName: "Mary", lastName: "Mean"),
        (firstName: "Foo", lastName: "Bar"),
        (firstName: "John", lastName: "Doe")
    ]
    
     persons2[1].firstName     // "Bar"
    

    These are proper arrays and adressed as such using subscripts. The dictionary type is usually a combination of key and value, i.e. nickname as key, and name as value.

    var nickNames : [String:String] =  [
        "mame" : "Mary Mean",
        "foba" : "Foo Bar",
        "jodo" : "John Doe"]
    
    nickNames["mame"]!  // "Mary Mean"
    

    And here we lookup on the key value, and get an optional value in return, which I forcefully unwrapped...

    All of these can be appended rather easily, but do note that the named tuple variant, persons2, is not following recommended practice. Also note that the Array of Dictionaries allow for inclusion on different keys as suggested in my last injection.

    persons1.append( Name(firstName: "Some", lastName: "Guy") )
    persons2.append( firstName: "Another", lastName: "Girl" )
    
    nickNames["anna"] = "Ann Nabel"
    
    // Array of Dictionaries
    var persons : [[String:String]] = [
        [ "firstName" : "Firstly", "lastName" : "Lastly"],
        [ "firstName" : "Donald", "lastName" : "Duck"]
    ]
    
    persons.append( ["firstName" : "Georg", "middleName" : "Friedrich", "lastName" : "Händel"] )
    

提交回复
热议问题