ios - Having only one element of array to be sorted in my case -


i have list of string:

var namelist = ["apple", "watermelon", "orange", ...] 

the list returned backend, order not garanteed.

i want have orange 1st element in array, no need care other elements' order.

i try use namelist.sort { $0 // do}, stuck, because want 1 element first element.

how achieve it?

====== update ======

a followup question. if have list of fruit objects, each fruit custom struct object:

struct fruit {   public let name;   public let weight;    init(_ name: string, _ weight: double) {      self.name = name      self.weight = weight   }  } 

now, got list of fruit:

var fruitlist:[fruit] = getdatafrombackend() 

i have fruit name "orange" first item, how now?

you can find index of "orange", , swap 0-th index:

if let indexoforange = namelist.index(of: "orange") {     if indexoforange != 0 {         swap(&namelist[0], &namelist[indexoforange])     } } 

if list can have multiple oranges, use snippet instead:

let sorted = namelist.filter {$0 == "orange"} + namelist.filter {$0 != "orange"} 

it concatenates list of oranges list of non-oranges.


Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -