How to Create 2D array in Swift?

前端 未结 3 1859
轻奢々
轻奢々 2021-01-16 06:43

Hi there I am new to Swift, I am trying to save Longitude and Latitude and place name from map\'s coordinate object to an Multidimensional array i.e:

Can anyone plea

3条回答
  •  感动是毒
    2021-01-16 07:18

    You can make an array of dictionaries, but I suggest using structs instead.

    Array of dictionaries

    Create an empty array of dictionaries:

    var pinArray = [[String:AnyObject]]()
    

    Append dictionaries to the array:

    pinArray.append(["lat":51.130231, "lon":-0.189201, "place":"home"])
    
    pinArray.append(["lat":52.130231, "lon":-1.189201, "place":"office"])
    

    But since your dictionaries hold two types of value (Double and String) it will be cumbersome to get the data back:

    for pin in pinArray {
        if let place = pin["place"] as? String {
            print(place)
        }
        if let lat = pin["lat"] as? Double {
            print(lat)
        }
    }
    

    So, better use structs instead:

    Array of structs

    Create a struct that will hold our values:

    struct Coordinates {
        var lat:Double
        var lon:Double
        var place:String
    }
    

    Create an empty array of these objects:

    var placesArray = [Coordinates]()
    

    Append instances of the struct to the array:

    placesArray.append(Coordinates(lat: 51.130231, lon: -0.189201, place: "home"))
    
    placesArray.append(Coordinates(lat: 52.130231, lon: -1.189201, place: "office"))
    

    It's then easy to get the values:

    for pin in placesArray {
        print(pin.place)
        print(pin.lat)
    }
    

提交回复
热议问题