Objective c Swift中的返回信号方法
我在Obj-C中有以下方法:Objective c Swift中的返回信号方法,objective-c,swift,racsignal,Objective C,Swift,Racsignal,我在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
- (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中使用此地图时遇到问题:
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
您的Swift代码顶部有
import CoreLocation
吗?@dpassage:是的,我只是为了了解CLLocationCoordinate2D
错误而加入了它。我已经更新了我的问题。这不起作用,因为map
不是NSDictionary
的成员。我的代码正在工作,我只是不确定这是否是正确的方法。那么Objective-C代码是如何工作的?谁将map
添加到NSDictionary
?我认为这是一个特殊的RACSignal
返回映射。在Objective-C中fetchJSONFromURL
是否返回NSDictionary
?不,它返回RACSignal
。