【发布时间】:2015-09-09 01:35:27
【问题描述】:
我一直在尝试将自定义 CGRect 函数从 Objective-C 转换为 Swift。
我会取得一些小的进展,但我总是会陷入困境。这是Objective-C中的工作函数:
CGRect CGRectSmallestWithCGPoints(NSMutableArray *pointsArray, int numberOfPoints) {
NSValue *firstValue = pointsArray[0];
CGFloat greatestXValue = [firstValue CGPointValue].x;
CGFloat greatestYValue = [firstValue CGPointValue].y;
CGFloat smallestXValue = [firstValue CGPointValue].x;
CGFloat smallestYValue = [firstValue CGPointValue].y;
for(int i = 1; i < numberOfPoints; i++) {
NSValue *value = pointsArray[i];
CGPoint point = [value CGPointValue];
greatestXValue = MAX(greatestXValue, point.x);
greatestYValue = MAX(greatestYValue, point.y);
smallestXValue = MIN(smallestXValue, point.x);
smallestYValue = MIN(smallestYValue, point.y);
}
CGRect rect;
rect.origin = CGPointMake(smallestXValue, smallestYValue);
rect.size.width = greatestXValue - smallestXValue;
rect.size.height = greatestYValue - smallestYValue;
return rect;
}
这是我目前使用Swift 转换的地方:
func CGRectSmallestWithCGPoints(pointsArray: NSArray, numberOfPoints: Int) -> CGRect {
var greatestXValue = pointsArray[0].x
var greatestYValue = pointsArray[0].y
var smallestXValue = pointsArray[0].x
var smallestYValue = pointsArray[0].y
for(var i = 1; i < numberOfPoints; i++)
{
let point = pointsArray[i];
greatestXValue = max(greatestXValue, point.x);
greatestYValue = max(greatestYValue, point.y);
smallestXValue = min(smallestXValue, point.x);
smallestYValue = min(smallestYValue, point.y);
}
var rect = CGRect()
rect.origin = CGPointMake(smallestXValue, smallestYValue);
rect.size.width = greatestXValue - smallestXValue;
rect.size.height = greatestYValue - smallestYValue;
return rect;
}
错误始于 for 循环。当我尝试使用 max 和 min 时,它给了我以下错误:
Cannot assign a value of type 'CLHeadingComponentValue' (aka 'Double') to a value of type 'CLHeadingComponentValue!'
然后在 for 循环之后,当我修改 rect 值时,它给了我一个类似的错误:
Cannot assign a value of type 'CLHeadingComponentValue' (aka 'Double') to a value of type 'CGFloat'
我很难理解为什么这种转换看起来如此困难。在过去的几周里,我一直在断断续续地使用 Swift,我一直在某些事情上陷入困境,比如 optional 的一些概念,但之前从未被困在某件事上这么久。
我正在使用带有 Swift 2 的 Xcode 7 测试版,非常感谢您的帮助。
【问题讨论】:
标签: swift swift2 xcode7 cgrect