Before WWDC I encountered a weird behavior in Swift 1.2 where structures caused memory leaks. I posted a question about this issue on Stack Overflow: http://stackoverflow.com/questions/30628547/memory-leak-in-swift-structures-how-to-fix-this
Now I tested this problem with Swift 2.0 and sadly it's not fully resolved. Since the old dev forums are now obsolete as far as I understand it, I'll try to explain the issue once again here.
I'm developing an application in Swift and I'm trying to use value types (structs and enums) where possible. According to the documentation about memory management, working with value types should not cause any memory problems and it should just work. But I found a situation where memory is leaking when using structs. And because it's in my event handling code, the leaks are pretty big.
Let's say there is a protocol
Item
which defines a single property value
:protocol Item {
var value: String { get }
}
We then create a concrete struct which implements the
Item
protocol and adds an additional generic property additionalValue
of type T. Let's call the struct FooItem
.struct FooItem<T>: Item {
let value: String
let additionalValue: T
init(value: String, additionalValue: T) {
self.value = value
self.additionalValue = additionalValue
}
}
The third piece of the puzzle is another struct which wraps an item implementing the
Item
protocol. It's called ItemWrapper
.struct ItemWrapper {
let item: Item
init(item: Item) {
self.item = item
}
}
Every time an ItemWrapper value is created with a FooItem, there is a memory leak shown in Instruments.
let item = FooItem(value: "protocol value", additionalValue: "foo item value")
let _ = ItemWrapper(item: item)
You can look for some Intruments screenshot in the original question posted on Stack Overflow: http://stackoverflow.com/questions/30628547/memory-leak-in-swift-structures-how-to-fix-this
There is also a Gist with the whole code: https://gist.github.com/lukaskubanek/4e3f7657864103d79e3a
I'd like to ask whether this is a bug or whether I am doing anything wrong? Thanks for any help with this issue!
The issue was resolved in Xcode 7 beta 5: http://stackoverflow.com/a/31936407/670119