0

What is the best way to convert this objective-c sorting method?

let visibleViews = self.scrollView.visibleViews().sorted(by: {$0.frame.origin.x > $1.frame.origin.x} ) 

I convert to :

[visibleViews sortUsingComparator:^NSComparisonResult(UIView *obj1, UIView *obj2) { return obj1.frame.origin.x > obj2.frame.origin.x; }]; 

I want to sort values to put the view with the larger xOrigin first (so the first item in the array will be the view on the right side of the screen). But I don't get the expected result.

2
  • 2
    “But I don't get the expected result.” is not constructive. What is the input, expected output, and actual output? Please post a minimal reproducible example. – Are you aware that the Swift code returns the sorted array, whereas the Objective-C code sorts the array in-place? Commented May 24, 2019 at 12:51
  • Using the > operator does not give the required NSComparisonResult result. Commented May 24, 2019 at 14:35

1 Answer 1

1

The return type of the sortUsingComparator block is NSComparisonResult. But your implementation is returning a type of BOOL.

One solution would be to use:

[visibleViews sortUsingComparator:^NSComparisonResult(UIView *obj1, UIView *obj2) { return [@(obj1.frame.origin.x) compare:@(obj2.frame.origin.x)]; }]; 

Note that a complete translation would be:

NSArry *visibleViews = [[self.scrollView visibleViews] sortedArrayUsingComparator:^NSComparisonResult(UIView *obj1, UIView *obj2) { return [@(obj1.frame.origin.x) compare:@(obj2.frame.origin.x)]; }]; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.