I noticed a strange behaviour of XCode using swiftUI's withAnimation{}.
I created the following working example:
import SwiftUI
class Block: Hashable, Identifiable {
// Note: this needs to be a class rather than a struct
var id = UUID()
static func == (lhs: Block, rhs: Block) -> Bool {
lhs.id == rhs.id
}
func hash(into hasher: inout Hasher) {
hasher.combine(self.id)
}
}
struct ContentView: View {
@State private var blocks: [Block]
init() {
var blocks = [Block]()
/// generate some blocks here
blocks.append(Block())
blocks.append(Block())
blocks.append(Block())
self._blocks = State(initialValue: blocks)
}
var body: some View {
VStack {
ForEach(blocks, id: \.self) { block in
BlockRow(block: block) { b in
print("COMMENT THIS LINE OUT") // try commenting out this line -> XCODE won't build anymore
withAnimation {
self.blocks.remove(at: self.blocks.firstIndex(of: b)!)
}
}
}
}
}
}
struct BlockRow: View {
@State var block: Block
var onDelete: (Block) -> Void = {_ in}
var body: some View {
Text("<Block>")
.onTapGesture {
print("Tap block \(block.id)")
self.onDelete(block)
}
}
}
The above example works as expected, if you click on one of the blocks it get's deleted and the following blocks will nicly slide in the free position.
But XCode produces a warning here, I do not understand:
Result of call to 'withAnimation' is unused
Things get even more confusing: by just commenting out the print stamenet beforehand the withAnimation block /* print("COMMENT THIS LINE OUT") */ XCode will no longer build the project:
Failed to produce diagnostic for expression; please file a bug report
Is this a bug or am I completely off-road with my aproach?