It looks like what you want is your function to return the pin code.
(看起来您想要的是返回PIN码的函数。)
You can do that as follows: (您可以按照以下步骤进行操作:)
func parsePinCode(fromJson json: Data) -> String? {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(MapModel.self, from: json)
let format = decodedData.results[0].formatted_address
var pinCode:String!
for item in decodedData.results[0].address_components{
if item.types[0] == "postal_code"{
pinCode = (item.long_name)
// Return the pinCode if we found one
return pinCode
}
}
} catch {
print(error)
}
return nil
}
You can use this function by calling it from other swift files as follows (where myJsonData
is the json data you want to decode):
(您可以通过从其他swift文件中调用此函数来使用此函数,如下所示(其中myJsonData
是要解码的json数据):)
let pinCode = parsePinCode(fromJson: myJsonData)
EDIT:
(编辑:)
If you want to return multiple values, you could create a struct with all the values you want to return.
(如果要返回多个值,则可以使用所有要返回的值创建一个结构。)
For example: (例如:)
struct MapData {
var pinCode: String?
var address: String?
}
func parsePinCode(fromJson json: Data) -> MapData? {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(MapModel.self, from: json)
var mapData = MapData()
mapData.address = decodedData.results[0].formatted_address
for item in decodedData.results[0].address_components {
if item.types[0] == "postal_code" {
mapData.pinCode = (item.long_name)
break
}
}
return mapData
} catch {
print(error)
}
return nil
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…