How to Create 2D array in Swift?

前端 未结 3 1474
感动是毒
感动是毒 2021-01-16 06:26

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 06:54

    Without more information, this is what I can offer.

    var pinArray = [[AnyObject]]()
    
    for location in mapLocations {
        var innerArray = [location["latitude"], location["longitude"], location["place"]]
        pinArray.append(innerArray)
    }
    
    0 讨论(0)
  • 2021-01-16 07:03

    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)
    }
    
    0 讨论(0)
  • 2021-01-16 07:10

    Solution using an enum for Lat/Lon/Place (as you don't show us what these are):

    enum Pos {
        case Lat
        case Lon
        case Place
    
        static let allPositions = [Lat, Lon, Place]
    }
    
    var myMatrix = [[Pos:Any]]()
    myMatrix.append([.Lat: 51.130231, .Lon: -0.189201, .Place: "Home"])
    myMatrix.append([.Lat: 52.130231, .Lon: -1.189201, .Place: "Office"])
    myMatrix.append([.Lat: 42.131331, .Lon: -1.119201, .Place: "Dinner"])
    
    /* check */
    for (i,vector) in myMatrix.enumerate() {
        for pos in Pos.allPositions {
            print("myMatrix[\(i)][\(pos)] = \(vector[pos] ?? "")")
        }
    }
    /*
    myMatrix[0][Lat] = 51.130231
    myMatrix[0][Lon] = -0.189201
    myMatrix[0][Place] = Home
    myMatrix[1][Lat] = 52.130231
    myMatrix[1][Lon] = -1.189201
    myMatrix[1][Place] = Office
    myMatrix[2][Lat] = 42.131331
    myMatrix[2][Lon] = -1.119201
    myMatrix[2][Place] = Dinner    */
    
    0 讨论(0)
提交回复
热议问题