您好我是Swift的新手,我正在尝试保存经度和纬度,并将地图的坐标对象放置到多维数组中,即:
有谁可以帮助我如何动态创建这些?
var pinArray[0][Lat] = 51.130231
var pinArray[0][Lon] = -0.189201
var pinArray[0][Place] = "Home"
var pinArray[1][Lat] = 52.130231
var pinArray[1][Lon] = -1.189201
var pinArray[1][Place] = "Office"
var pinArray[2][Lat] = 42.131331
var pinArray[2][Lon] = -1.119201
var pinArray[2][Place] = "Dinner"
答案 0 :(得分:1)
没有更多信息,这就是我能提供的。
var pinArray = [[AnyObject]]()
for location in mapLocations {
var innerArray = [location["latitude"], location["longitude"], location["place"]]
pinArray.append(innerArray)
}
答案 1 :(得分:1)
使用enum for Lat / Lon / Place的解决方案(因为你没有告诉我们这些是什么):
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 */
答案 2 :(得分:1)
你可以创建一个字典数组,但我建议改用结构。
创建一个空的字典数组:
var pinArray = [[String:AnyObject]]()
将字典附加到数组:
pinArray.append(["lat":51.130231, "lon":-0.189201, "place":"home"])
pinArray.append(["lat":52.130231, "lon":-1.189201, "place":"office"])
但是,由于您的词典包含两种类型的值(Double和String),因此获取数据将非常麻烦:
for pin in pinArray {
if let place = pin["place"] as? String {
print(place)
}
if let lat = pin["lat"] as? Double {
print(lat)
}
}
因此,最好使用结构:
创建一个包含我们值的结构:
struct Coordinates {
var lat:Double
var lon:Double
var place:String
}
创建这些对象的空数组:
var placesArray = [Coordinates]()
将结构的实例追加到数组中:
placesArray.append(Coordinates(lat: 51.130231, lon: -0.189201, place: "home"))
placesArray.append(Coordinates(lat: 52.130231, lon: -1.189201, place: "office"))
然后很容易得到这些值:
for pin in placesArray {
print(pin.place)
print(pin.lat)
}