我正在尝试将 PNChart 添加到我的 Swift 2.0 应用程序中。
我有一个函数,我想将它转换为 2.0,但我一直收到错误。
在 swift 1.2 中
actualData.getData = {(index: NSInteger) -> PNLineChartDataItem in
var yValue:CGFloat = array[index]
var item = PNLineChartDataItem(y: yValue)
return item
}
在 objective-c 中
actualData.getData = ^(NSUInteger index) {
NSNumber* value = array[index];
CGFloat yValue = [value longValue];
return [PNLineChartDataItem dataItemWithY:yValue];
};
在 Swift 2.0 中我得到了错误
Cannot assign a value of type ((NSInteger) -> PNLineChartDataItem) to a value of type LCLineChartDataGetter!
最佳答案
您的 LCLineChartDataGetter
定义为:
typedef PNLineChartDataItem *(^LCLineChartDataGetter)(NSUInteger item);
(注意 NSUInteger
中的 U
)
而您向它传递了一个 NSInteger
。将 NSInteger
更改为 NSUInteger
,它应该可以工作。
同样在 Swift 中,您可以从此简化闭包的头部:
actualData.getData = {(index: NSUInteger) -> PNLineChartDataItem in
// ...
return item
}
为此并让它推断出类型:
actualData.getData = {index in
// ...
return item
}
或者甚至用这个替换整个闭包,让 Swift 为您施展魔法:
actualData.getData = { PNLineChartDataItem(y: array[$0]) }
关于ios - 从 Swift 1.2 转换为 2 - 变量函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31438071/