Sorting Arrays in Swift 4 - iOS 11 - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

14 Oct 2017

Sorting Arrays in Swift 4 - iOS 11

Sorting Arrays using swift 4 is a simple using sorted() built-in method.

Sorting Arrays in Swift 4 - iOS 11

Here is a example for sorting an simple array containing string objects.
let friends = ["Sophia", "James", "Olivia", "Mike", "Nina"]
print(friends.sorted())

//output is '["James", "Mike", "Nina", "Olivia", "Sophia"]'

We can sort complex arrays also easily using same built-in method sorted().

Creating an array with custom struct:

struct friendStruct {
    var name: String
    var age: Int
}

let array = [
    friendStruct(name: "Sophia", age: 23),
    friendStruct(name: "Olivia", age: 25),
    friendStruct(name: "James", age: 21),
    friendStruct(name: "Nina", age: 26),
    friendStruct(name: "Mike", age: 23)
]

Sort by name:

let sortedArray = array.sorted { (firstStruct, secondStruct) -> Bool in
    if firstStruct.name < secondStruct.name {
        return true
    }
    return false
}

Sort by age:

let sortedArray = array.sorted { (firstStruct, secondStruct) -> Bool in
    if firstStruct.age < secondStruct.age {
        return true
    }
    return false
}


We can sort Date also like above.

5 Ways To Concatenate/Merge Two Arrays into One Array in Swift 4

No comments:

Post a Comment

Post Top Ad