我有一個閉包函式,我想在其中分配一個默認值,但我收到一個錯誤,因為默認引數不允許在元組型別中使用
func getResponse(address: String, completion : @escaping ((_ lat : CLLocationDegrees, _ long : CLLocationDegrees, _ attributedPlaceName: String, _ placeId: String? = nil)->())) {
}
uj5u.com熱心網友回復:
你需要做一個老式的多載,即
有3個引數:
func getResponse(
address: String,
completion: @escaping (
(
_ lat: CLLocationDegrees,
_ long: CLLocationDegrees,
_ attributedPlaceName: String
) -> ()
)
) {
//
}
getResponse(address: "foo") { lat, long, attributedPlaceName in
//
}
有4個引數:
func getResponse(
address: String,
completion: @escaping (
(
_ lat: CLLocationDegrees,
_ long: CLLocationDegrees,
_ attributedPlaceName: String,
_ placeId: String?
) -> ()
)
) {
//
}
getResponse(address: "bar") { lat, long, attributedPlaceName, placeId in
//
}
雖然我真的不知道你為什么要打擾。如果您只有 4 引數簽名,則可以使用下劃線隨意忽略任何引數,即
getResponse(address: "bar") { lat, long, attributedPlaceName, _ in
//
}
uj5u.com熱心網友回復:
不要使用多個引數,而是定義一個模型來保存您的資料:
struct Place {
let latitude: CLLocationDegrees
let longitude: CLLocationDegrees
let attributedName: String
let id: String?
init(
latitude: CLLocationDegrees,
longitude: CLLocationDegrees,
attributedName: String,
id: String? = nil
) {
self.latitude = latitude
self.longitude = longitude
self.attributedName = attributedName
self.id = id
}
}
并使用該型別:
func getResponse(address: String, completion: @escaping (Place) -> Void) {
}
您的代碼將更容易閱讀,并且您在Place初始化程式中隱藏了默認引數值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/409130.html
標籤:
