-1

Everyone I have a array of following File object

File{
var displayName: String? // eg detail.txt, abc.doc
var size: Int?
..
}

say, I have a array of this file object

let arrayOfFile = [f1,f2,f3,f4.....f1000];

These file objects are getting display in a UITableView over a screen. There are a search option, where user can search files... Now the problem is, when user type something into UISearchBar I need to sort arrayOfFile array in such a way that the File object which contains search string (within name) comes first (all in alphabetic sorted order) and other files which doesn't contains search string within name come at the end.

this is what I have tried so far...

self.dataArray =  self.searchDataSource.sorted(by: { ( f1, f2) -> Bool in
    if f1.displayName.lowercased().strContains(text) && f2.displayName.lowercased().strContains(text){
                            if f1.displayName.localizedCaseInsensitiveCompare(f2.displayName) == ComparisonResult.orderedAscending{
                                return true;
                            }
                            else if f1.displayName.localizedCaseInsensitiveCompare(f2.displayName) == ComparisonResult.orderedSame{
                                return true;
                            }
                            else if f1.displayName.localizedCaseInsensitiveCompare(f2.displayName) == ComparisonResult.orderedDescending{
                                return false;
                            }
                            else{
                                return false;
                            }
                        }
                        else if f1.displayName.lowercased().strContains(text){
                            return  true
                        }else if f2.displayName.lowercased().strContains(text){
                            return true
                        }
                        else{
                            return false
                        }
                       })
Suryakant Sharma
  • 3,852
  • 1
  • 25
  • 47
  • In pseudo code: `if (f1...contains(text) && !f2...contains(text)){return true}else if (!f1...contains(text) && f2...contains(text)){return false} else {return f1.displayName.caseInsensitiveCompare(f2.diplayName) != .orderedAscending }` or something like that? Logic similar: https://stackoverflow.com/questions/45674976/sort-nsarray-custom-object-on-multiple-properties/45689734#45689734 where "is of custom type" is equivalent to "contains(text)". – Larme Nov 17 '17 at 13:42

1 Answers1

0

Best way to do this would be to make your ‘File’ class conform to ‘comparable’. Then call sort method on the File array.

bibintomj
  • 73
  • 5