夫特4 - 的Xcode 9的β4 - NSKernAttributeName VS NSAttributedStringKey

问题描述:

iOS的部署目标:iOS的9.3, 基地SDK:最新的IOS(iOS的11.0), 的Xcode 9 Beta 4的, 夫特4夫特4 - 的Xcode 9的β4 - NSKernAttributeName VS NSAttributedStringKey

下面的代码建立和运行在夫特3时,Xcode 8:

let kern = (CTRunGetAttributes(run) as? [String : Any])? 
[NSKernAttributeName] as? CGFloat ?? 0 

然而,夫特4迁移它转换成这样的:

let kern = (CTRunGetAttributes(run) as? [String : Any])? 
[NSAttributedStringKey.kern] as? CGFloat ?? 0 

Xcode的9现在抱怨:

Cannot subscript a value of type '[String : Any]' with an index of type 'NSAttributedStringKey' 

据探长说,“NSAttributedStringKey”仅在iOS的11提供(请记住,我中定位iOS 9)。

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

命令点击'NSKernAttributeName'告诉我它的可用性是iOS 6.但是,检查员也声称它的类型是'NSAttributedStringKey',它只在iOS 11中可用。我不知道这是否仅仅是一个API演示文稿的伪装,或者一些东西,或者我错过的东西。

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

谢谢你的帮助。

将字典键入为[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。

+0

谢谢你。解释非常感谢。 – Womble

textField.defaultTextAttributes[NSAttributedStringKey.kern.rawValue] = 16 

斯威夫特4

如果你不想忽略警告,无论投,你可以将它们复制到一个新的字典干净。

var attributes: [NSAttributedStringKey: Any] = [:] 
textField.defaultTextAttributes.forEach{ 
    attributes[NSAttributedStringKey(rawValue: $0.key)] = $0.value 
}