如何将此语法Swift转换为Objective-C

时间:2017-01-21 12:09:54

标签: ios objective-c swift sorting

我正在将Swift项目转换为Objective-C。当我转换代码时,我不知道它是正确还是错误。

夫特

let closest = layoutAttributes.sorted {
    abs($0.center.x - proposedContentOffsetCenterOrigin) < abs($1.center.x - proposedContentOffsetCenterOrigin)
}.first ?? UICollectionViewLayoutAttributes()

目标-C

UICollectionViewLayoutAttributes *closest = [[layoutAttributes sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    return
        fabsf([(UICollectionViewLayoutAttributes*)a center].x - proposedContentOffsetCenterOrigin)
        <
        fabsf([(UICollectionViewLayoutAttributes*)b center].x - proposedContentOffsetCenterOrigin);
}] firstObject];

1 个答案:

答案 0 :(得分:2)

您可以稍微简化代码。 Obj-C中的返回值也必须不同。

UICollectionViewLayoutAttributes *closest = [[layoutAttributes sortedArrayUsingComparator:^NSComparisonResult(UICollectionViewLayoutAttributes *a, UICollectionViewLayoutAttributes *b) {
    CGFloat distanceA = ABS(a.center.x - proposedContentOffsetCenterOrigin);
    CGFloat distanceB = ABS(b.center.x - proposedContentOffsetCenterOrigin);

    if (distanceA < distanceB) {
        return NSOrderedAscending;
    } else if (distanceA > distanceB) {
        return NSOrderedDescending;
    }

    return NSOrderedSame;
}] firstObject];

Swift ?? UICollectionViewLayoutAttributes()将被翻译为?: [[UICollectionViewLayoutAttributes alloc] init];,但如果您的数组不为空,则不需要它。