我有两个数组:
var latitude = [100,200,300]
var longitude = [55,66,77]
我正在尝试制作这个新阵列:
var coordinate = [[100,55],[200,66],[300,77]]
但它不起作用。这是我的代码:
var latitude = [100,200,300]
var longitude = [55,66,77]
var x = 0
var y = 0
var coordinate = []
for lat in latitude{
x = lat
for long in longitude{
y = long
}
coordinate = [x,y]
}
coor
这是我得到的:
[300,77]
只有最后两个元素。
答案 0 :(得分:5)
尝试使用以下代码。这对你来说非常合适,
var latitude = [100,200,300]
var longitude = [55,66,77]
var x = 0
var y = 0
var coordinate = Array<Array<Int>>()
var i = 0
for lat in latitude{
x = lat
y = longitude[i++]
coordinate.append(Array(x,y))
}
干杯..!
更新1:
var latitude = [100,200,300]
var longitude = [55,66,77]
var coordinate = Array<Array<Int>>()
for (lat,lon) in zip(latitude,longitude){
coordinate.append(Array(arrayLiteral: lat,lon))
}
答案 1 :(得分:4)
这是一个建议。代码中的评论。
var latitude = [100,200,300] // OK, so these are arrays of Ints
var longitude = [55,66,77] // Is that what you want? Doubles or floats might be more appropriate
var x = 0 // Why declare these out here? In the loop is ok
var y = 0 // You are also forcing them to Ints (and vars, not lets, though you're not changing them)
/* This IS a bit of a mess
for lat in latitude{
x = lat // This should be ok, but no need to declare x outside the loop
for long in longitude { // This is wrong - you will always get the last longitude
y = long
}
coordinate = [x,y] // where is coordinate declared, and as what?
}
*/
// I'm not sure why you want an array of arrays - an array of tuples,
// or an array of structs seems more correct, as there will only ever be two elements
// in the inner "array". Here's a struct...
struct Coordinate {
var latitude : Int // As I said above, doubles might be better
var longitude : Int
}
var coordinates = Coordinate[]()
if latitude.count == longitude.count {
for i in 0..latitude.count {
coordinates += Coordinate(latitude:latitude[i], longitude:longitude[i])
}
println("Coordinates = \(coordinates)")
} else {
println("Mismatch in length of ordinate arrays")
}
更新的 要使用数组数组(这是实际问题),请考虑这个
typealias IntArray = Array<Int> // Again, probably should be doubles...
var coordinateArray = IntArray[]()
for i in 0..min(latitude.count, longitude.count) {
coordinateArray += [latitude[i], longitude[i]]
}
答案 2 :(得分:1)
您应该尝试定义允许存储的类型Array,类型应该是Dictionary
这样的事情:
var latitude: Float[] = [100,200,300]
var longitude: Float[] = [55,66,77]
var coordinate = Array<Dictionary>()
var i: Int = 0;
for lat in latitude {
let coor: Dictionary<String, Float> = ["x":lat, "y": longitude[i]]
coordinate.append(coor)
i++;
}