arrays - How to swap two dates in swift -
trying swap 2 dates in swift. gives me error saying:
cannot subscript value of type '[mission]' index of type 'int'
func sort (mission: [mission]) -> bool { (var = 0; < 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 }
this function named sort, doesn't sort array. if you're trying sort array, should use builtin sort function:
missions.sort { $0.createdat.timeintervalsince1970 > $1.createdat.timeintervalsince1970 }
the function you've written it, compilable, cause fatalerror because try access out-of-bounds index. i
goes 1 count - 1
, try mission[i+1]
. fix should change range of loop stop @ count - 2
.
the error compiler giving caused fact function parameters immutable default, assignments aren't possible. if want changes visible outside function, you'll need mark argument inout
.
further, swap should use swift's builtin swap
function instead of implementing yourself. putting of together:
func sort(inout mission: [mission]) -> bool { 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 }
Comments
Post a Comment