You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 4升级后NSAttributedStringKey下标错误:NSColor修复求助

解决Swift 4中NSAttributedString属性键的错误问题

嘿,这个坑我升级Swift 4的时候也踩过!其实原因很直白:Swift 4开始,NSAttributedString的属性字典类型从[String: Any]改成了[NSAttributedStringKey: Any],所有原来的字符串属性键都被封装成了NSAttributedStringKey枚举里的静态属性,不能再直接用字符串下标访问了。

你已经搞定了字体的部分,颜色对应的枚举值是NSAttributedStringKey.foregroundColor,替换掉原来的"NSColor"字符串就行。

修正前的错误代码:

attributes["NSFont"] = font
attributes["NSColor"] = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1)

修正后的正确代码:

attributes[NSAttributedStringKey.font] = font
attributes[NSAttributedStringKey.foregroundColor] = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1)

额外提个小细节:原来的"NSColor"其实对应旧版的NSForegroundColorAttributeName常量,所以Swift 4里对应的枚举就是.foregroundColor。以后碰到其他属性(比如下划线、背景色),都可以去NSAttributedStringKey枚举里找对应的静态属性,比如.underlineStyle、.backgroundColor,都是一一对应的。

内容的提问来源于stack exchange,提问作者j.doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:34:53