1

我在 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 中使用此地图时遇到问题:

return [[self fetchJSONFromURL:url] map:^(NSDictionary *json) {
    return [MTLJSONAdapter modelOfClass:[WXCondition class] fromJSONDictionary:json error:nil];
}];

一切都在正确编译,但是有没有更好的方法呢?

4

1 回答 1

1

我没有在项目中尝试过,但也许这会做

return fetchJSONFromURL(url).map { (json: NSDictionary) in
    return MTLJSONAdapter.modelOfClass(WXCondition.self, fromJSONDictionary: json, error: nil)
} as RACSignal
于 2014-06-13T15:10:52.933 回答