我正在尝试遍历数组并获取坐标,但它给了我一个错误,我无法访问我的数组。数据通过一个序列传递,如果我打印它表明它正在工作,因此数据可以正确传输,但无法弄清楚为什么我不能遍历数组并提取纬度和经度。
这是控制台的输出。
DeliveryDestinations(NameOrBusiness: Optional("In-N-Out Burger"),
FirstLineAddress: Optional("550 Newhall Dr"), SecondLineAddress:
Optional(" United States"), CityLineAddress: Optional(" San Jose"),
PostcodeLineAddress: Optional(" CA 95110"), DistanceToDestination:
Optional(9.2807823200000001), Lat: Optional(37.350253606833043), Long:
Optional(-121.92182779312132))
import UIKit
import MapKit
import CoreLocation
class DeliveryLocationsVC: UIViewController {
@IBOutlet weak var mapView: MKMapView!
var addressArr = [DeliveryDestinations]()
override func viewDidLoad() {
super.viewDidLoad()
print(addressArr)
navigationItem.title = "Delivery Location"
// Do any additional setup after loading the view.
for (theKey, theValue) in addressArr { //<-- error can't access the elements in array
if (theKey == "Lat") {
if let coordinateseliveryDestinations = theValue {
print (coordinates)
}
print("Item \(theKey): \(theValue)")
}
}
}
}
我的数组来自下面的结构
import Foundation
import MapKit
struct DeliveryDestinations {
var NameOrBusiness: String?
var FirstLineAddress: String?
var SecondLineAddress: String?
var CityLineAddress: String?
var PostcodeLineAddress: String?
var DistanceToDestination: CLLocationDistance?
var Lat: Double?
var Long: Double?
init(NameOrBusiness: String?, FirstLineAddress: String?, SecondLineAddress: String?, CityLineAddress: String?, PostCodeLineAddress: String?, DistanceToDestination: CLLocationDistance?, Lat: Double?, Long: Double? ) {
self.NameOrBusiness = NameOrBusiness
self.FirstLineAddress = FirstLineAddress
self.SecondLineAddress = SecondLineAddress
self.CityLineAddress = CityLineAddress
self.PostcodeLineAddress = PostCodeLineAddress
self.DistanceToDestination = DistanceToDestination
self.Lat = Lat
self.Long = Long
}
}
Best Answer-推荐答案 strong>
你有一个数组(而不是字典),所以你需要做的是像这样迭代:
for object in addressArr {
...
// get coordinates from object
let lat = object.Lat
let long = object.Long
}
或者,如果您还需要表格行的索引,您可以这样做:
for (i, object) in addressArr.enumerated() {
...
// get coordinates from object
let lat = object.Lat
let long = object.Long
print ("Destination at index \(i) has coordinate: (\(lat), \(long))")
}
我怎么知道它是一个数组?
代码中的符号
var addressArr = [DeliveryDestinations]()
总是意味着,这是一个DeliveryDestinations对象数组。
当您将其打印出来时,您会打印出数组中的对象。
在你的情况下,这个对象有一个“像字典一样”的描述,所以 print 函数像这样打印它。
在每个对象中,使用 description 函数,您可以指定在对象(或这些对象的数组)上打印时文本的外观
关于ios - 快速迭代数组时出错,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/47994547/
|