[swift-users] ARC // Precise Lifetime Semantics

Daniel Eggert danieleggert at me.com
Tue Jan 5 09:57:01 CST 2016

How do I extend the lifetime of a variable, i.e. make sure that ARC is less aggressive?

clang has an attribute called objc_precise_lifetime — does Swift have something similar?

I have this code:

  do {
    var base = UnsafePointer<Void>()
    var size = Int()
    let mapped = dispatch_data_create_map(backingData, &base, &size)
    let buffer = UnsafeBufferPointer<A>(start: UnsafePointer<A>(base), count: size / sizeof(A))
    return someFunction(buffer)

I need the ‘mapped’ variable to stay in scope (i.e. not be released) until the end of the scope, but ARC is free to release it immediately — in fact the compiler warns me that the immutable value is never used.

But the API contract with dispatch_data_create_map(3) is that the values in ‘base’ and ‘size’ are only valid as long as ‘mapped’ is around. The above code is passing a buffer into ‘someFunction’ that’s no longer valid.

How do I fix this?


More information about the swift-users mailing list