How to swap two dates in swift

139 views Asked by At

Trying to swap two dates in Swift. It currently gives me an error saying:

Cannot subscript a value of type '[Mission]' with an index of type 'Int'

func sort (mission: [Mission]) -> Bool {
    for (var i = 0; i < mission.count; i++) {
        println(mission[i].createdAt)
        if mission[i].createdAt.timeIntervalSince1970 > mission[i+1].createdAt.timeIntervalSince1970 {
            var temp = mission[i]
            mission[i] = mission[i+1]
            mission[i+1] = temp
        }
    }
    println()
    return true
}
1

There are 1 answers

1
ahruss On BEST ANSWER

This function is named sort, but it doesn't actually sort the array. If you're actually trying to sort the array, you should just use the builtin sort function:

missions.sort { $0.createdAt.timeIntervalSince1970 > $1.createdAt.timeIntervalSince1970 }

The function as you've written it, were it compilable, would always cause a fatalError because you always try to access an out-of-bounds index. i goes from 1 to count - 1 and then you try to do mission[i+1]. To fix this you should change the range of the for loop to stop at count - 2.

The error the compiler is giving you is actually caused by the fact that function parameters are immutable by default, so your assignments aren't actually possible. If you want your changes to be visible outside the function, you'll need to mark the argument inout.

Further, to do the swap you should use swift's builtin swap function instead of implementing it yourself. Putting all of that together:

func sort(inout mission: [Mission]) -> Bool {
    for i in 0..<mission.count-1 {
        println(mission[i].createdAt)
        if mission[i].createdAt.timeIntervalSince1970 > mission[i+1].createdAt.timeIntervalSince1970 {
            swap(&mission[i], &mission[i+1])
        }
    }
    println()
    return true
}