好的,这是我在使用 CGImageSource 时遇到的一个案例,并注意到 CFDictionary 和 NSDictionary 之间的免费桥接在某些情况下似乎遇到了问题。我设法构建了以下示例来说明我的意思:
func optionalProblemDictionary() -> CFDictionary? {
let key = "key"
let value = "value"
var keyCallBacks = CFDictionaryKeyCallBacks()
var valueCallBacks = CFDictionaryValueCallBacks()
let cfDictionary = CFDictionaryCreate(kCFAllocatorDefault, UnsafeMutablePointer(unsafeAddressOf(key)), UnsafeMutablePointer(unsafeAddressOf(value)), 1, &keyCallBacks, &valueCallBacks)
return cfDictionary
}
相当简单(也有点傻),但它是一个返回函数和可选的 CFDictionary。当试图从这个函数创建一个 NSDictionary 时,“乐趣”就开始了:
为什么以下不起作用?
if let problemDictionary = optionalProblemDictionary() as? NSDictionary {
print(problemDictionary) // never enters, no warnings, compiles just fine
}
虽然这工作正常?
if let cfDictionary = optionalProblemDictionary() {
let problemDictionary = cfDictionary as NSDictionary
print(problemDictionary)
}
XCode 7.0 (7A220)