gpt4 book ai didi

ios - 在 Swift 3 中使用未声明的类型

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:02:13 31 4
gpt4 key购买 nike

我有以下类返回 NOAA 气象观测站列表。我用它来学习如何处理 XML。但是,我在 func returnWxStation() -> (wxObservationStations) 处收到“使用未声明的类型‘wxObservationStations’”错误。我正在使用 SWXMLHash 反序列化 XML,但我不认为这是我的问题(虽然我只是在学习,所以它可能是)。

class WxObservationStations {

let wxObserStationsURL = URL(string: "http://w1.weather.gov/xml/current_obs/index.xml")

struct wxStation: XMLIndexerDeserializable {
let stationName: String
let stationState: String
let latitude: Double
let longitude: Double

static func deserialize(_ node: XMLIndexer) throws -> wxStation {
return try wxStation(
stationName: node["station_name"].value(),
stationState: node["state"].value(),
latitude: node["latitude"].value(),
longitude: node["longitude"].value()
)
}
}

public var wxObservationStations: [wxStation] = []


private func getStationNamesAndLocations(url: URL, completion:@escaping (XMLIndexer) -> ()) {

Alamofire.request(url).responseJSON { response in
// print(response) // To check XML data in debug window.
let wxStationList = SWXMLHash.parse(response.data!)
print(wxStationList)
completion(wxStationList)

}
}

//The error is here:
func returnWxStation() -> (wxObservationStations) {
getStationNamesAndLocations(url: wxObserStationsURL!, completion: { serverResponse in
do {
self.wxObservationStations = try serverResponse["wx_station_index"]["station"].value()

} catch {

}
})
return self.wxObservationStations
}
}

有什么想法吗?该变量在类中声明,我想用它来将数据发送回请求对象。提前致谢。

最佳答案

wxObservationStations 不是类型,所以这样说是没有意义的

func returnWxStation() -> (wxObservationStations) { ... }

你正在返回 self.wxObservationStations,它是 [wxStation] 类型。所以方法声明应该是

func returnWxStation() -> [wxStation] { ... }

顺便说一句,如果您坚持使用 Cocoa 命名约定,您的生活将会轻松得多,即类型应该以大写字母开头。因此,我建议不要使用 wxStation 类型,而是使用 WxStation


您的以下方法不会实现您想要的:

func returnWxStation() -> [wxStation] {
getStationNamesAndLocations(url: wxObserStationsURL!, completion: { serverResponse in
do {
self.wxObservationStations = try serverResponse["wx_station_index"]["station"].value()
} catch {

}
})

return self.wxObservationStations
}

getStationNamesAndLocations 方法异步运行,您的 self.wxObservationStations 不会在 returnWxStation 实际返回时填充。

getStationNamesAndLocations 方法的全部目的是为您提供一个带有完成处理程序的漂亮异步方法。我将从您的代码中完全删除 returnWxStation。或者做类似的事情:

func returnWxStation(completionHandler: ([wxStation]?) -> Void) {
getStationNamesAndLocations(url: wxObserStationsURL!) { serverResponse in
do {
let stations = try serverResponse["wx_station_index"]["station"].value()
completionHandler(stations)
} catch {
completionHandler(nil)
}
}
}

你会像这样使用它:

returnWxStation() { stations in
guard let stations = stations else {
// handle error here
return
}

// use `stations` here
}

// but not here

关于ios - 在 Swift 3 中使用未声明的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41315510/

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