Toll-free bridging and pointer access in Swift

前端 未结 5 1833
轮回少年
轮回少年 2020-12-13 19:33

I am porting an App from Objective-C to Swift and I need to use the following method:

CFStreamCreatePairWithSocketToHost(alloc: CFAllocator!, host: CFString!         


        
5条回答
  •  有刺的猬
    2020-12-13 20:18

    I worked out how to do it. A few important notes:

    1. CMutablePointers will be automatically created if you use the & operator.
    2. You can get at the T in an Unmanaged with .getUnretainedValue() and getRetainedValue() (Seems .getUnretainedValue() is analogous to __bridge_transfer)
    3. Optionals are automatically initialised to nil.
    4. If an optional is nil it will translate into a false condition.

    So far I have (untested):

    var readStream: Unmanaged?
    var writeStream: Unmanaged?
    
    CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, host, port, \
    &readStream, &writeStream)
    
    if (readStream && writeStream) {
        inputStream = readStream!.takeUnretainedValue();
        outputStream = writeStream!.takeUnretainedValue();
    }
    

提交回复
热议问题