【问题标题】:How to remove this object from a Swift array? [duplicate]如何从 Swift 数组中删除这个对象? [复制]
【发布时间】:2017-04-02 19:58:55
【问题描述】:

从数组中删除 formattedCoordinate 的合适命令是什么?我知道 Objective-C 存在 removeObject,但是 Swift 呢?

var markersArray: Array<CLLocationCoordinate2D> = []

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker){
    let lat: CLLocationDegrees = marker.position.latitude
    let lng: CLLocationDegrees = marker.position.longitude
    var formattedCoordinate = CLLocationCoordinate2D(latitude: lat,longitude: lng)
    //markersArray.remove(formattedCoordinate) need to fix this
    self.clean()
    //    return 0; not sure if we need this here
}

func mapView(_ mapView: GMSMapView, didBeginDragging marker: GMSMarker){
    let lat: CLLocationDegrees = marker.position.latitude
    let lng: CLLocationDegrees = marker.position.longitude
    var formattedCoordinate = CLLocationCoordinate2D(latitude: lat,longitude: lng)
    // markersArray.remove(formattedCoordinate) need to fix this
}

【问题讨论】:

  • 在你的行中的 formattedCoordinate 前面加上一个 at: 并删除
  • 查看关于集合的 swift 语言指南部分:developer.apple.com/library/content/documentation/Swift/…
  • @Konyv12 array.remove(at:Index).提供索引值
  • 考虑到欺骗目标,剩下的唯一问题是CLLocationCoordinate2D 不(无论出于何种原因)符合Equatable - 这样做相当简单,例如参见stackoverflow.com/a/27364437/2976878
  • 但是用户可能会点击之前绘制的标记,因此它并不总是需要删除的数组的最后一个成员。

标签: swift cllocationcoordinate2d


【解决方案1】:

建议

self.markersArray = self.markersArray.filter({ !(($0.latitude == formattedCoordinate.latitude) && ($0.longitude == formattedCoordinate.longitude)) })

【讨论】:

  • 是的,我的错,修好了,对不起。
  • 我有一个多维数组。这对它有用吗?
  • @konyv12 还没有尝试过,但是由于过滤器得到了closure,理论上它应该,如果你调整这个代码不使用CLLocationCoordinate2D,而是使用[Class]
  • 你所说的 [Class] 到底是什么意思?
猜你喜欢
  • 2012-07-24
  • 1970-01-01
  • 2016-09-10
  • 1970-01-01
  • 2017-01-28
  • 2012-06-17
  • 1970-01-01
  • 1970-01-01
  • 2013-04-24
相关资源
最近更新 更多