[swift-users] Callback in Swift
Rien
Rien at Balancingrock.nl
Wed Jan 25 03:50:59 CST 2017
> On 25 Jan 2017, at 10:33, John Brownie <john_brownie at sil.org> wrote:
>
> Thanks, that does it for me, though I had to qualify the Unmanaged with a type in the first part.
>
> Rien wrote:
>> For the context I passed in:
>>
>> UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
>>
>> And to get the context back inside the callback:
>>
>> let ourself = Unmanaged< … your type here…>.fromOpaque(arg!).takeUnretainedValue()
>>
>> Then “ourself” was the object normally obtained as “self”.
>>
> A more general question is how to learn these tricks. The worst pain I've had in learning Swift is how to handle interactions with frameworks in other languages, such as this one (Cocoa) or the Expat parser (C). The Swift book doesn't even mention Unmanaged or opaque. The book on using Swift with Objective-C mentions Unmanaged, but not opaque (apart from a couple of references, neither of which mentions toOpaque/fromOpaque. If there were a reference that gathered these things together in one place, it would be easier to learn than simply thrashing around for a while and asking for help.
I usually start off with using the debugger. And I like to print out pointer values a lot. Shows you how swift handles them.
After that I usually know what to look for and am able to target my googling.
Subscribing to lists (and scanning posts) like these (and evolution) also makes you more aware of what is going on. In isolation it is difficult to get a good feel for a language.
Rien
> --
> John Brownie
> In Finland on furlough from SIL Papua New Guinea
More information about the swift-users
mailing list