ios - 快速迭代数组时出错
<p><p>我正在尝试遍历数组并获取坐标,但它给了我一个错误,我无法访问我的数组。数据通过一个序列传递,如果我打印它表明它正在工作,因此数据可以正确传输,但无法弄清楚为什么我不能遍历数组并提取纬度和经度。</p>
<p>这是控制台的输出。</p>
<blockquote>
<p>DeliveryDestinations(NameOrBusiness: Optional("In-N-Out Burger"),
FirstLineAddress: Optional("550 Newhall Dr"), SecondLineAddress:
Optional(" United States"), CityLineAddress: Optional(" San Jose"),
PostcodeLineAddress: Optional(" CA95110"), DistanceToDestination:
Optional(9.2807823200000001), Lat: Optional(37.350253606833043), Long:
Optional(-121.92182779312132))</p>
</blockquote>
<pre><code>import UIKit
import MapKit
import CoreLocation
class DeliveryLocationsVC: UIViewController {
@IBOutlet weak var mapView: MKMapView!
var addressArr = ()
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 coordinates:DeliveryDestinations = theValue {
print (coordinates)
}
print("Item \(theKey): \(theValue)")
}
}
}
}
</code></pre>
<p>我的数组来自下面的结构</p>
<pre><code>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
}
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>你有一个数组(而不是字典),所以你需要做的是像这样迭代:</p>
<pre><code>for object in addressArr {
...
// get coordinates from object
let lat = object.Lat
let long = object.Long
}
</code></pre>
<p>或者,如果您还需要表格行的索引,您可以这样做:</p>
<pre><code>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))")
}
</code></pre>
<p>我怎么知道它是一个数组?</p>
<p>代码中的符号</p>
<pre><code> var addressArr = ()
</code></pre>
<p>总是意味着,这是一个DeliveryDestinations对象数组。
当您将其打印出来时,您会打印出数组中的对象。
在你的情况下,这个对象有一个“像字典一样”的描述,所以 print 函数像这样打印它。 </p>
<p>在每个对象中,使用 <code>description</code> 函数,您可以指定在对象(或这些对象的数组)上打印时文本的外观</p></p>
<p style="font-size: 20px;">关于ios - 快速迭代数组时出错,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/47994547/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/47994547/
</a>
</p>
页:
[1]