Swapping values


I’m trying get the dragging/dropping of rows in a UITableView to work. I’ve been at this for days.

If I delete the data and let the app rebuild it, the first time I run the app and drag a cell it will work as expected. After that it wont swap at all or will do so at what seems like random with other cells. I can rerun the app but it still acts up until I delete the data and start over.

For example. I will swap rows 0 and 1. That works. I can see the placement numbers swap in Realm Studio like I would expect. When I try to swap them back however, nothing happens. If I step through the 2 lines of code in the write block. The first line updates like I expect, I can verify that in the debugger. As soon as I execute the second line not only does it not update, the first line rubberbands back to its original value. I have rewritten this several times now and keep getting the same results. I just can’t figure out what I am doing wrong.

This seems to me like more of a Realm issue than a Swift one but I could be wrong.

 func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let draggedPlacement = currentSongLyrics[sourceIndexPath.row].placement
        let destPlacement = currentSongLyrics[destinationIndexPath.row].placement
        try! realm.write {
            currentSongLyrics[destPlacement].placement = draggedPlacement
            currentSongLyrics[draggedPlacement].placement = destPlacement


There could be 100 other things causing the issue you’re describing. Moreover, it’s unclear how everything is being kept in sync. In other words, assuming your tableView is being fed by a tableView dataSource, that doesn’t appear to be updated - just realm. Or do you have an observer
refreshing the dataSource? Or something else?


I have a Songs class and a Lyrics class in a many to many relationship. Songs holds things like the song title, Lyrics holds the actual lyrics, the type of lyric (verse, chorus etc) and it’s placement in the song. CurrentSongLyrics is an instance of lyrics that I load up and sort on the .placement property when this VC loads, like so currentSongLyrics = currentSongLyrics.sorted(byKeyPath: "placement"). The plan is to swap the 2 .placement property values and resort the array. I’m using Swifty Beaver to log most every function in the app, I’ve stepped through it many times and I cant see where the data might be getting overwritten, it just is.

If I understand what you mean by observer, no Im not using one. Wouldn’t currentSongLyrics be my dataSource? Sorry still real new to all of this.