NSCF对象不能直接转为Swift本地对象

NSCF对象不能直接转为Swift本地对象

今天在Playground 中测试一段ImageIO读取GIF图片的代码。
一直报错。

通过不断注释代码,来排查问题,发现是下面一段代码产生了错误。

1
let gifProperties = CGImageSourceCopyProperties(src!, nil) as! Dictionary<String, AnyObject>

CGImageSourceCopyProperties函数返回类型为NSCFDictionary。

我们知道在OC代码中,NSCFDictionary和NSDictionary是可以相互替代的。

swift中Dictionary和NSDictionary是可以相互替代的。

如果把代码修改为

1
let gifProperties = CGImageSourceCopyProperties(src!, nil) as! Dictionary<String, AnyObject>

则显示gifProperties的值为nil。

如果改为

1
2
let gifProperties = CGImageSourceCopyProperties(src!, nil)
print(gifProperties.dynamicType)

则gifProperties的值确实为一个字典类型。
print语句输出内容为: __NSCFDictionary

最后把代码修改为

1
2
let gifProperties_ = CGImageSourceCopyProperties(src!, nil) as? NSDictionary
let gifProperties = (gifProperties_! as NSDictionary) as? Dictionary<String, AnyObject>

不能直接转换的原因,估计应该是苹果没有对这个转换做特殊处理。从NSCFDictionary和NSDictionary实质是有一个类型的转换过程,而从NSCFDictionary到Dictionary缺乏类型信息的过度,所以转换失败。

Array类和Set类也存在同样的问题。