如何创建斯威夫特二维数组? [英] How to Create 2D array in Swift?
问题描述
您好我是新来的斯威夫特,我想保存经纬度和地名从地图的坐标对象的多维数组即:
任何人都可以请帮我我如何这些动态创建?
VAR pinArray [0] [纬度] = 51.130231
VAR pinArray [0] [经度] = -0.189201
VAR pinArray [0] [地方] =家变种pinArray [1] [纬度] = 52.130231
变种pinArray [1] [经度] = -1.189201
VAR pinArray [1] [地方] =办公室变种pinArray [2] [纬度] = 42.131331
变种pinArray [2] [经度] = -1.119201
VAR pinArray [2] [地方] =晚餐
您可以字典的数组,但我建议使用结构来代替。
词典阵列
创建词典的空数组:
VAR pinArray = [[字符串:AnyObject]()
字典追加到数组:
pinArray.append([纬度:51.130231,LON: - 0.189201,地方:家])pinArray.append([纬度:52.130231,LON: - 1.189201,地方:办公室])
但你的字典持有两种类型的值(双和字符串),这将是累赘取回数据:
在pinArray {销
如果让地方=针[地方]作为?字符串{
打印(地方)
}
如果让经纬度=针[纬度]作为?双{
打印(LAT)
}
}
所以,更好地利用结构来代替:
结构的数组
创建一个结构,将举行我们的价值观:
结构坐标{
VAR纬度:双
VAR LON:双
VAR的地方:字符串
}
创建这些对象的空数组:
VAR placesArray = [坐标]()
追加结构的实例数组:
placesArray.append(坐标(纬度:51.130231,经度:-0.189201,地点:家))placesArray.append(坐标(纬度:52.130231,经度:-1.189201,地点:办公室))
这是再容易得到的值:
在placesArray {销
打印(pin.place)
打印(pin.lat)
}
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 please help me how do i create these dynamically?
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"
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)
}
这篇关于如何创建斯威夫特二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!