Swift how to sort array of custom objects by property value

前端 未结 18 2067
逝去的感伤
逝去的感伤 2020-11-22 02:12

lets say we have a custom class named imageFile and this class contains two properties.

class imageFile  {
    var fileName = String()
    var fileID = Int(         


        
相关标签:
18条回答
  • 2020-11-22 02:31

    You return a sorted array from the fileID property by following way:

    Swift 2

    let sortedArray = images.sorted({ $0.fileID > $1.fileID })
    

    Swift 3 OR 4

    let sortedArray = images.sorted(by: { $0.fileID > $1.fileID })
    

    Swift 5.0

    let sortedArray = images.sorted {
        $0.fileID < $1.fileID
    }
    
    0 讨论(0)
  • 2020-11-22 02:33

    Two alternatives

    1) Ordering the original array with sortInPlace

    self.assignments.sortInPlace({ $0.order < $1.order })
    self.printAssignments(assignments)
    

    2) Using an alternative array to store the ordered array

    var assignmentsO = [Assignment] ()
    assignmentsO = self.assignments.sort({ $0.order < $1.order })
    self.printAssignments(assignmentsO)
    
    0 讨论(0)
  • 2020-11-22 02:35

    Swift 3 & 4 & 5

    I had some problem related to lowercase and capital case

    so I did this code

    let sortedImages = images.sorted(by: { $0.fileID.lowercased() < $1.fileID.lowercased() })
    

    and then use sortedImages after that

    0 讨论(0)
  • 2020-11-22 02:40

    If you want to sort original array of custom objects. Here is another way to do so in Swift 2.1

    var myCustomerArray = [Customer]()
    myCustomerArray.sortInPlace {(customer1:Customer, customer2:Customer) -> Bool in
        customer1.id < customer2.id
    }
    

    Where id is an Integer. You can use the same < operator for String properties as well.

    You can learn more about its use by looking at an example here: Swift2: Nearby Customers

    0 讨论(0)
  • 2020-11-22 02:41

    In Swift 3.0

    images.sort(by: { (first: imageFile, second: imageFile) -> Bool in
        first. fileID < second. fileID
    })
    
    0 讨论(0)
  • 2020-11-22 02:43

    With Swift 5, Array has two methods called sorted() and sorted(by:). The first method, sorted(), has the following declaration:

    Returns the elements of the collection, sorted.

    func sorted() -> [Element]
    

    The second method, sorted(by:), has the following declaration:

    Returns the elements of the collection, sorted using the given predicate as the comparison between elements.

    func sorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element]
    

    #1. Sort with ascending order for comparable objects

    If the element type inside your collection conforms to Comparable protocol, you will be able to use sorted() in order to sort your elements with ascending order. The following Playground code shows how to use sorted():

    class ImageFile: CustomStringConvertible, Comparable {
    
        let fileName: String
        let fileID: Int
        var description: String { return "ImageFile with ID: \(fileID)" }
    
        init(fileName: String, fileID: Int) {
            self.fileName = fileName
            self.fileID = fileID
        }
    
        static func ==(lhs: ImageFile, rhs: ImageFile) -> Bool {
            return lhs.fileID == rhs.fileID
        }
    
        static func <(lhs: ImageFile, rhs: ImageFile) -> Bool {
            return lhs.fileID < rhs.fileID
        }
    
    }
    
    let images = [
        ImageFile(fileName: "Car", fileID: 300),
        ImageFile(fileName: "Boat", fileID: 100),
        ImageFile(fileName: "Plane", fileID: 200)
    ]
    
    let sortedImages = images.sorted()
    print(sortedImages)
    
    /*
     prints: [ImageFile with ID: 100, ImageFile with ID: 200, ImageFile with ID: 300]
     */
    

    #2. Sort with descending order for comparable objects

    If the element type inside your collection conforms to Comparable protocol, you will have to use sorted(by:) in order to sort your elements with a descending order.

    class ImageFile: CustomStringConvertible, Comparable {
    
        let fileName: String
        let fileID: Int
        var description: String { return "ImageFile with ID: \(fileID)" }
    
        init(fileName: String, fileID: Int) {
            self.fileName = fileName
            self.fileID = fileID
        }
    
        static func ==(lhs: ImageFile, rhs: ImageFile) -> Bool {
            return lhs.fileID == rhs.fileID
        }
    
        static func <(lhs: ImageFile, rhs: ImageFile) -> Bool {
            return lhs.fileID < rhs.fileID
        }
    
    }
    
    let images = [
        ImageFile(fileName: "Car", fileID: 300),
        ImageFile(fileName: "Boat", fileID: 100),
        ImageFile(fileName: "Plane", fileID: 200)
    ]
    
    let sortedImages = images.sorted(by: { (img0: ImageFile, img1: ImageFile) -> Bool in
        return img0 > img1
    })
    //let sortedImages = images.sorted(by: >) // also works
    //let sortedImages = images.sorted { $0 > $1 } // also works
    print(sortedImages)
    
    /*
     prints: [ImageFile with ID: 300, ImageFile with ID: 200, ImageFile with ID: 100]
     */
    

    #3. Sort with ascending or descending order for non-comparable objects

    If the element type inside your collection DOES NOT conform to Comparable protocol, you will have to use sorted(by:) in order to sort your elements with ascending or descending order.

    class ImageFile: CustomStringConvertible {
    
        let fileName: String
        let fileID: Int
        var description: String { return "ImageFile with ID: \(fileID)" }
    
        init(fileName: String, fileID: Int) {
            self.fileName = fileName
            self.fileID = fileID
        }
    
    }
    
    let images = [
        ImageFile(fileName: "Car", fileID: 300),
        ImageFile(fileName: "Boat", fileID: 100),
        ImageFile(fileName: "Plane", fileID: 200)
    ]
    
    let sortedImages = images.sorted(by: { (img0: ImageFile, img1: ImageFile) -> Bool in
        return img0.fileID < img1.fileID
    })
    //let sortedImages = images.sorted { $0.fileID < $1.fileID } // also works
    print(sortedImages)
    
    /*
     prints: [ImageFile with ID: 300, ImageFile with ID: 200, ImageFile with ID: 100]
     */
    

    Note that Swift also provides two methods called sort() and sort(by:) as counterparts of sorted() and sorted(by:) if you need to sort your collection in-place.

    0 讨论(0)
提交回复
热议问题