所以我在解包和可选方面遇到了一些问题。我正在使用谷歌地点并传递两次place.formattedAddress值...首先从 GMSAutocompleteViewController 到 UIView 以显示在字符串中。然后我想在用户确认地点后将place.formattedAddress传递给Firebase。我能够将选定的 GMSPlace 传递到 UIView 中,但是一旦我调用 confirmAddPlace(( 函数,它就会在第行崩溃>让 placeID2 = place.placeID 并给我"终止与未捕获的 NSException 类型的异常"。我相信这与解包和可选有关......我对这个概念还是有些陌生的。感谢您的任何帮助!
// Pass GMSPlace to UIView string
// MARK: GOOGLE AUTO COMPLETE DELEGATE
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
let placeID = place.placeID
placesClient.lookUpPlaceID(placeID, callback: { (place, error) -> Void in
if let error = error {
print("lookup place id query error: (error.localizedDescription)")
return
}
guard let place = place else {
print("No place details for (placeID)")
return
}
print("Place name (place.name)")
print("Place address (place.formattedAddress)")
})
let selectedPlace = place.formattedAddress
if let name = selectedPlace as String!
{
self.placeNameLabel.text = "Are you sure you would like to add (name) to your places?"
}
self.dismiss(animated: true, completion: nil)
setupConfirmationPopUp()
}
// user taps confirm button to send item to be updated in Firebase
func confirmAddPlace(place: GMSPlace!) {
let accessToken = FBSDKAccessToken.current()
guard let accessTokenString = accessToken?.tokenString else { return }
let credentials = FIRFacebookAuthProvider.credential(withAccessToken: accessTokenString)
FIRAuth.auth()?.signIn(with: credentials, completion: { (user, error) in
if error != nil {
print("Something went wrong with our FB user: ", error ?? "")
return
}
// create place on tap pf confirm
let placeID2 = place.placeID
guard let place = place else {
print("No place details for (placeID2)")
return
}
let confirmedPlace = place.formattedAddress
if let confirmedPlace = confirmedPlace as String!
{
self.placeNameLabel.text = "(confirmedPlace)"
}
let ref = FIRDatabase.database().reference().child("places")
let childRef = ref.childByAutoId()
let values = ["place": self.placeNameLabel.text, "name": user!.displayName]
childRef.updateChildValues(values)
})
animateOut()
}
不要在 func 中强制解开参数。要么将它们设置为可选,要么将它们用作其类型。
对于可选:
func confirmAddPlace(place: GMSPlace?) {
...
...
let placeID2 = place?.placeID
...
...
}
对于按原样使用它们的类型:(但为此,您必须使用解包的值调用此 func,例如:confirmAddPlace(myPlace!)
(
func confirmAddPlace(place: GMSPlace) {
...
...
let placeID2 = place.placeID
...
...
}
但是,如果您确实想坚持您的实现,那么您可以像这样交换:
guard let place = place else {
return
}
let placeID2 = place.placeID
如果您传递的place
有可疑之处,这将从您的 func 返回