简体   繁体   中英

How to convert this syntax Swift into Objective-C

I'm converting a Swift project into Objective-C. And when I convert follow code, I don't know it's correct or wrong.

Swift

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

Objective-C

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

You can simplify the code a bit. Also the return value has to be different in 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];

The Swift ?? UICollectionViewLayoutAttributes() ?? UICollectionViewLayoutAttributes() would be translated as ?: [[UICollectionViewLayoutAttributes alloc] init]; but you don't need that there if your array is not empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM