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.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/

相关文章:

ios - 重置定时器信号的最佳方法是什么?

ios - 重试 RACObserve 直到成功

iphone - 定义机器系统功能的设计策略建议

dependency-injection - Swift 的对象框架宏

ios - collat​​ionStringSelector 错误 : Unrecognized selector

ios - 如何将 Struct 传递给需要 AnyObject 的方法?

ios - 有人根据 RACSignal 制作了自更新可变 TableView 吗?

iphone - 如果 UITableview 为空显示图像

iphone - 如何解散两个或多个dismissModalViewController?

iphone - iOS动画下雪