从Swift调用Core-Foundation方法

时间:2014-11-03 19:08:01

标签: swift core-foundation

我熟悉Obj-c并熟悉Swift,但是我正在为Swift非常严格的类型检查而苦苦挣扎。举个例子,我想做的就是转换下面的Obj-c中的例程:

- (void)receiveIncomingConnectionNotification:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSFileHandle *incomingFileHandle = [userInfo objectForKey:NSFileHandleNotificationFileHandleItem];

    if (incomingFileHandle) {
        CFDictionaryAddValue(
            incomingRequests,
            (__bridge const void *)(incomingFileHandle),
            (__bridge const void *)((__bridge id)CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE)));
    }
}

Swift:

func receiveIncomingConnectionNotification(notification: NSNotification) {
    let userInfo: NSDictionary = notification.userInfo!
    let incomingFileHandle: NSFileHandle? = userInfo.objectForKey(NSFileHandleNotificationFileHandleItem) as? NSFileHandle
    if (incomingFileHandle != nil) {
        CFDictionaryAddValue(self.incomingRequests as CFMutableDictionaryRef, incomingFileHandle, CFHTTPMessageCreateEmpty(kCFAllocatorDefault, true))
    }
}

但CFDictionaryAddValue调用一直产生错误,指向“true”参数,表示“Cannot convert the expression's type '(CFMutableDictionaryRef, NSFileHandle?, Unmanaged<CFHTTPMessage>!' to type BooleanLiteralConvertible!

任何人都知道正确的方法,或者BooleanLiteralConvertible是什么?

1 个答案:

答案 0 :(得分:0)

如果你一次考虑一个论点,那就更清楚了:

let m = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, 1).takeRetainedValue()
let f = incomingFileHandle!
let d = self.incomingRequests as CFMutableDictionaryRef
CFDictionaryAddValue(d, unsafeAddressOf(f), unsafeAddressOf(m))
  • C布尔值必须表示为数字。

  • CFHTTPMessageCreateEmpty需要内存管理,因为它以非托管方式返回。

  • 您的incomingFileHandle是可选的;它需要展开。

  • CFDictionaryAddValue需要不安全的地址(UnsafePointer)。