Swift 4 - Xcode 9 beta 4 - NSKernAttributeName vs NSAttributedStringKey

Wom*_*ble 3 xcode ios swift4 xcode9-beta

iOS部署目标:iOS 9.3,基础SDK:最新iOS(iOS 11.0),Xcode 9 Beta 4,Swift 4

以下代码在Swift 3,Xcode 8中构建和运行:

    let kern = (CTRunGetAttributes(run) as? [String : Any])?
[NSKernAttributeName] as? CGFloat ?? 0
Run Code Online (Sandbox Code Playgroud)

但是,Swift 4迁移器将其转换为:

    let kern = (CTRunGetAttributes(run) as? [String : Any])?
[NSAttributedStringKey.kern] as? CGFloat ?? 0
Run Code Online (Sandbox Code Playgroud)

Xcode 9现在抱怨:

Cannot subscript a value of type '[String : Any]' with an index of type 'NSAttributedStringKey'
Run Code Online (Sandbox Code Playgroud)

根据检查员的说法,' NSAttributedStringKey'仅适用于iOS 11.(请记住,我的目标是iOS 9).

如果我将' NSAttributedStringKey.kern' 替换为' NSKernAttributeName',则错误仍然存​​在.

按住命令' NSKernAttributeName'告诉我它的可用性是iOS 6.但是,检查员还声称它的类型是' NSAttributedStringKey',这仅在iOS 11中可用.我不知道这是否仅仅是API演示的假象,或者是一种东西,或者我缺少的东西.

问题:如何使用NSKernAttributeName(或其现代化版本)向后兼容iOS 9和Swift 4?

感谢您的任何帮助.

Cha*_*tka 8

键入字典为[NSAttributedStringKey:Any]而不是[String:Any].它是Swift叠加层中的所有糖,因此它甚至可以在较旧的macOS/OS X版本上运行.

编辑:我应该澄清我的最后一句话.NSAttributedStringKey以及Swift 4中的所有其他新"Key"类型仅存在于Swift中,而不存在于Objective-C中.当具有NSAttributedStringKey键的字典桥接到Objective-C时,所有键都将变为NSStrings.由于您正在使用的实际Foundation,UIKit等框架是用C/Objective-C编写的,这将"正常工作",您不必担心声明NSAttributedStringKey的文档仅为10.11.