从 swift 中的 MKLocalSearch 对象中检索第一个 'mapItem' 元素

Retrieve first 'mapItem' element from MKLocalSearch object in swift

首先我想说我是 swift 语言的新手。

我的问题几乎反映了这个问题:

但是,当我将其应用于外观相似的代码时,出现错误 "Value of type 'MKLocalSearch' has no member 'mapItems'"

就像上面的 link 一样,我想要第一个 mapItems (mapItems[0]) 结果。 有人可以帮助我吗?

这是我的代码:

    let latitude = String(currentLocation.coordinate.latitude)
    let longitude = String(currentLocation.coordinate.longitude)

    var station1Unwrapped: String! = ""
    var station2Unwrapped: String! = ""

    var coord: CLLocationCoordinate2D!
    coord = CLLocationCoordinate2DMake(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
    var region: MKCoordinateRegion!
    region = MKCoordinateRegion(center: coord, latitudinalMeters: 100, longitudinalMeters: 100);

    let request = MKLocalSearch.Request()
    request.naturalLanguageQuery = "Train Station"
    request.region = region

    let search = MKLocalSearch(request: request)
    search.start { response, error in
        guard let response = response else {
            print("There was an error searching for: \(String(describing: request.naturalLanguageQuery)) error: \(String(describing: error))")
            return
        }

        print("Inside function")

        let station1 = response.mapItems[0].name


    }

    var newLocVar = (search.mapItems[0] as! MKMapItem).name
    print(newLocVar)

变量searchMKLocalSearch,所以它没有属性mapItems。如果你想打印 MKMapItem's name,你应该访问完成块中的 mapItems,在那里你可以访问 responseMKLocalSearch.Response。您写的 let station1 = response.mapItems[0].name 行完全正确,它包含找到的第一个 mapItems

的名称