【问题标题】:Accessing variables from one function to another Swift将变量从一个函数访问到另一个 Swift
【发布时间】:2016-12-24 00:34:51
【问题描述】:

所以这似乎是一个简单的问题,可能有一个非常简单的解决方案,但无法解决这个问题。我有一个在函数中形成的变量,我想在另一个函数中使用“newPlace”、“place”和“place.name”……如何使它成为非局部变量?我想将 storedPlaces.append(newPlace) 放入另一个函数中,但它告诉我 newPlace 是一个未定义的变量......显然,当我将 let newPlace=.... 放在类下面时,它不能识别'地方'。我试着把 var place: GMSPlace?在顶部,但这也不起作用。

下面是相关代码:

     func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {

        let camera = GMSCameraPosition.camera(withLatitude: place.coordinate.latitude, longitude: place.coordinate.longitude, zoom: 15.0)
        self.vwGMap.camera = camera
        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2DMake(place.coordinate.latitude, place.coordinate.longitude)
   marker.title = place.name
    marker.snippet = place.formattedAddress
        marker.map = self.vwGMap
        marker.icon = GMSMarker.markerImage(with: UIColor.blue)
        marker.tracksViewChanges = true
        self.dismiss(animated: true, completion: nil)
        print("Place name: ", place.name)
        print("Place address: ", place.formattedAddress)
        print("Place placeID: ", place.placeID)
        print("Place attributions: ", place.attributions)
        print("Place Coordinate:", place.coordinate)
        //The printing only happens in the terminal
        let newPlace = StoredPlace(name: place.name, address: place.formattedAddress!, placeID: place.placeID)
        storedPlaces.append(newPlace)

           }

这是类的顶部:

    var storedPlaces: [StoredPlace] = []

【问题讨论】:

  • 您的课程是否需要多次实例化?如果没有,你可以使用 Singleton。
  • 您是否像这样在类中的任何位置初始化了storedPlaces:确保您也没有在代码中的任何位置使数组无效。

标签: ios swift google-maps variables local-variables


【解决方案1】:

同样在类的顶部添加

var place:GMSPlace?
var newPlace:StoredPlace?

在你的函数中分配它们

func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
    self.place = place
    ....
    self.newPlace = StoredPlace(name: place.name, address: place.formattedAddress!, placeID: place.placeID)
}

【讨论】:

    猜你喜欢
    • 2022-10-24
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    相关资源
    最近更新 更多