我在 Obj-C 中有以下方法:
- (RACSignal *)fetchCurrentConditionsForLocation:(CLLocationCoordinate2D)coordinate {
NSString *urlString = [NSString stringWithFormat:@"http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&units=metric", coordinate.latitude, coordinate.longitude];
NSURL *url = [NSURL URLWithString:urlString];
return [[self fetchJSONFromURL:url] map:^(NSDictionary *json) {
return [MTLJSONAdapter modelOfClass:[WXCondition class] fromJSONDictionary:json error:nil];
}];
}
我对 Swift 的转换:
func fetchJSONFromURL(url: NSURL) -> RACSignal {
}
func fetchCurrentConditionsForLocation(coordinate: CLLocationCoordinate2D) -> RACSignal {
let urlString = NSString(format: "http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&units=metric", coordinate.latitude, coordinate.longitude)
let url = NSURL.URLWithString(urlString)
// Convert to Swift?
return [[self fetchJSONFromURL:url] map:^(NSDictionary *json) {
return [MTLJSONAdapter modelOfClass:[WXCondition class] fromJSONDictionary:json error:nil];
}];
}
在 Swift 中使用此 map 时遇到问题:
return [[self fetchJSONFromURL:url] map:^(NSDictionary *json) {
return [MTLJSONAdapter modelOfClass:[WXCondition class] fromJSONDictionary:json error:nil];
}];
一切都可以正确编译,但是有更好的方法吗?
最佳答案
我还没有在项目中尝试过,但也许这会做
return fetchJSONFromURL(url).map { (json: NSDictionary) in
return MTLJSONAdapter.modelOfClass(WXCondition.self, fromJSONDictionary: json, error: nil)
} as RACSignal
关于objective-c - 在 Swift 中返回 RACSignal 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24208133/