Swift 2 - UnsafeMutablePointer <Void>到对象

Swift 2 - UnsafeMutablePointer <Void>到对象

如果我有一个像这样的方法:

func someMethod(contextPtr: UnsafeMutablePointer<Void>)

我如何从中获取对象contextPtr

func someMethod(contextPtr: UnsafeMutablePointer<Void>){    
    let object:MyObject = contextPtr.memory}

得到:

'Void'不能转换为'MyObject'

什么是秘诀


更多详情:

我在这里做的是设置一个全局回调函数SCNetworkReachability

func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutablePointer<Void>) {

    let r:Reachability = info.memory}

然后添加回调如下:

var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)var s = selfwithUnsafeMutablePointer(&s) {
    context.info = UnsafeMutablePointer($0)}SCNetworkReachabilitySetCallback(reachability, callback, &context)


沧海一幻觉
浏览 480回答 2
2回答

qq_遁去的一_1

struct S {&nbsp; &nbsp; var i: Int = 10}var first = S()func foo(contextPtr: UnsafeMutablePointer<Void>){&nbsp; &nbsp; let pS = UnsafeMutablePointer<S>(contextPtr)&nbsp; &nbsp; pS.memory.i = 100}print(first.i) // 10foo(&first)print(first.i) // 100如果我们需要传递为UnsafeMutablePointer self到异步函数import XCPlaygroundXCPlaygroundPage.currentPage.needsIndefiniteExecution = trueimport Foundation// can be struct, class ...class C {&nbsp; &nbsp; let queue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT)&nbsp; &nbsp; var s: String = ""&nbsp; &nbsp; func foo() {&nbsp; &nbsp; &nbsp; &nbsp; var c = self&nbsp; &nbsp; &nbsp; &nbsp; dispatch_async(queue) { () -> Void in&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f(&c)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}func f(pV: UnsafeMutablePointer<Void>) {&nbsp; &nbsp; let pC = UnsafeMutablePointer<C>(pV)&nbsp; &nbsp; sleep(1)&nbsp; &nbsp; print(pC.memory.s)}var c1: C? = C()c1!.s = "C1"c1!.foo()&nbsp; &nbsp; &nbsp; &nbsp; // C1var c2: C? = C()c2!.s = "C2"c2!.foo()&nbsp; &nbsp; &nbsp; &nbsp; // C2c1 = nilc2 = nilprint("test")
打开App,查看更多内容
随时随地看视频慕课网APP