gpt4 book ai didi

objective-c - 以 Swift 方式将 Objective-C block 转换为闭包

转载 作者:搜寻专家 更新时间:2023-10-31 21:49:07 26 4
gpt4 key购买 nike

我已经成功地将以下方法从 Obj-C 转换为 Swift:

学习后如何blocks are replaced by closuresSwift 中。

Objective-C :

- (RACSignal *)fetchCurrentConditionsForLocation:(CLLocationCoordinate2D)coordinate {
NSString *urlString = [NSString stringWithFormat:@"http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&units=imperial", 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 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)

return fetchJSONFromURL(url).map { json in
return MTLJSONAdapter.modelOfClass(WXCondition.self, fromJSONDictionary: json as NSDictionary, error: nil)
}
}

但是,我无法将以下返回映射 block 转换为 Swift:

enter image description here

func fetchHourlyForecastForLocation(coordinate: CLLocationCoordinate2D) -> RACSignal {
var urlString = NSString(format: "http://api.openweathermap.org/data/2.5/forecast?lat=%f&lon=%f&units=metric&cnt=12", coordinate.latitude, coordinate.longitude)
let url = NSURL.URLWithString(urlString)

/* Original Obj-C:

return [[self fetchJSONFromURL:url] map:^(NSDictionary *json) {
RACSequence *list = [json[@"list"] rac_sequence];
return [[list map:^(NSDictionary *item) {
return [MTLJSONAdapter modelOfClass:[WXCondition class] fromJSONDictionary:item error:nil];
}] array];
}];
}
*/

// My attempt at conversion to Swift
// (I can't resolve `rac_sequence` properly). Kind of confused
// as to how to cast it properly and return
// it as an "rac_sequence" array.

return fetchJSONFromURL(url).map { json in
let list = RACSequence()
list = [json["list"] rac_sequence]
return (list).map { item in {
return MTLJSONAdapter.modelOfClass(WXCondition.self, fromJSONDictionary: item as NSDictionary, error: nil)
} as NSArray
}
}

如果有帮助,这就是 rac_sequence 的含义:

- (RACSequence *)rac_sequence {
return [RACArraySequence sequenceWithArray:self offset:0];
}

RACArraySequence():

+ (instancetype)sequenceWithArray:(NSArray *)array offset:(NSUInteger)offset;

编辑: fetch 方法返回 RACSignal不是 NSArray:

func fetchJSONFromURL(url: NSURL) -> RACSignal {

}

最佳答案

看起来您只是忘记了函数声明中的返回类型。声明应如下所示:

func fetchHourlyForecastForLocation(coordinate: CLLocationCoordinate2D) -> RACSignal { //...rest of function

因为返回类型现在已命名,所以您可以在函数末尾的 return 语句中删除 as NSArray 强制转换。希望这对您有所帮助!

关于objective-c - 以 Swift 方式将 Objective-C block 转换为闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24221862/

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