简体   繁体   中英

Custom sort objects in an array in swift

Needed to sort Objects (Class/Datatype), Alphabetically.

UnSorted Array::

[main.Apple, main.Zoo, main.IceCream, main.Apple, main.IceCream]

Sorted Array:: Alphabetically Type @ the Front

[main.Apple, main.Apple, main.IceCream, main.IceCream, main.Zoo]

This is one of the solutions that I have found till now:

  1. Make use of sortInPlace function and dynamicType to check for class names eg:- String(firstDataType.dynamicType).componentsSeparatedByString(".").last! this retrieves the class name for the Object.

     unsortedArray.sortInPlace({(firstDataType,secondDataType) in return String(firstDataType.dynamicType).componentsSeparatedByString(".").last! .localizedStandardCompare(String(secondDataType.dynamicType).componentsSeparatedByString(".").last!) == NSComparisonResult.OrderedAscending 

    })

    Demo Link

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