ios - Memory leak in Swift structures - How to fix this? -


i'm developing application in swift 2 (xcode 7 beta 3) , i'm trying use value types (structs , enums) possible. according apple's documentation memory management, working value types should not cause retain cycles , should work.

but today encountered huge amount of memory leaks in event handling code. tracked down , reduced problem following minimal example.

let's there protocol item defines single property value:

protocol item {      var value: string { }  } 

we create concrete struct implements item protocol , adds additional property additionalvalue. let's call 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 puzzle struct wraps item implementing item protocol. it's called itemwrapper.

struct itemwrapper {      let item: item      init(item: item) {         self.item = item     }  } 

if profiled in instruments using memory leaks configuration, memory leak appears every time itemwrapper value created fooitem.

let item = fooitem(value: "protocol value", additionalvalue: "foo item value")   let _ = itemwrapper(item: item)  

instruments screenshot 1 instruments screenshot 2

here example xcode project , instruments file: https://www.dropbox.com/s/z6ugxzxqggrv1xl/swiftstructsmemoryleak.zip?dl=0

the whole code example can viewed in gist: https://gist.github.com/lukaskubanek/4e3f7657864103d79e3a

here bug report: rdar://21375421

is bug in swift compiler or doing wrong?


edit 1: suggested in comments, reposted question on apple dev forum in order draw more attention swift community , potentially developers of language. due migration of dev forums during wwdc 2015 had post updated question on new forums. here link: https://forums.developer.apple.com/message/9643


edit 2: problem posted in example code seems resolved in swift 2.0. since didn't solve issues in app made modification example code. fooitem's additional property has generic type , fooitem annotated type , generic type. how i'm using in app , still causes memory leak, time when itemwrapper initialized rather when accessing property.


edit 3: updated question modified problem persists in swift 2.0 , uploaded new example xcode project.

although haven't got response apple neither on dev forums nor in bug tracker , haven't found related issue in release notes of latest beta versions, seems solved in swift compiler in xcode 7 beta 5. (maybe works in beta 4. last version i've checked beta 3.)

the demo project doesn't produce memory leak anymore. same true app. yay!

enter image description here


Comments