gpt4 book ai didi

ios - 从一个函数访问另一个 Swift 函数的变量

转载 作者:行者123 更新时间:2023-11-30 12:48:37 26 4
gpt4 key购买 nike

所以这似乎是一个简单的问题,可能有一个非常简单的解决方案,但无法解决这个问题。我在函数中形成了一个变量,我想在另一个函数中使用“newPlace”、“place”和“place.name”...如何使其成为非局部变量?我想将 StoredPlaces.append(newPlace) 放入另一个函数中,但它告诉我 newPlace 是一个 undefined variable ...显然,当我将 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] = []

最佳答案

也在类的顶部添加

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)
}

关于ios - 从一个函数访问另一个 Swift 函数的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41304715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com