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

创建String扩展从HTML生成字符串时遇'Type String has no member documentType'错误求助

解决"Type 'String' has no member 'documentType'"错误

这个错误的核心原因很明确:documentType并不是String类型的成员,它属于NSAttributedString.DocumentReadingOptionKey枚举。你在构建options字典时没有明确指定键的类型,导致Swift错误地从String类型下去查找这个成员,自然会抛出找不到的错误。

修正后的String扩展代码

下面是可以正常工作的完整扩展实现,我还补充了必要的错误处理(因为这个NSAttributedString的初始化方法会抛出异常):

extension String {
    func toAttributedStringFromHTML() -> NSAttributedString? {
        // 先将当前String转为UTF-8编码的Data
        guard let htmlData = self.data(using: .utf8) else {
            print("Failed to convert string to UTF-8 data")
            return nil
        }
        
        do {
            return try NSAttributedString(
                data: htmlData,
                options: [
                    // 明确指定键为NSAttributedString.DocumentReadingOptionKey的成员
                    NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
                    NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue
                ],
                documentAttributes: nil
            )
        } catch let error {
            print("Error generating attributed string from HTML: \(error.localizedDescription)")
            return nil
        }
    }
}

简化写法(Swift 5.7+)

如果你使用的是较新的Swift版本,可以利用类型推断简化代码,只要明确指定字典的类型即可:

options: [
    .documentType: NSAttributedString.DocumentType.html,
    .characterEncoding: String.Encoding.utf8.rawValue
] as [NSAttributedString.DocumentReadingOptionKey: Any]

这样Swift就能正确识别.documentType属于NSAttributedString.DocumentReadingOptionKey枚举,不会再出现类型匹配错误。

内容的提问来源于stack exchange,提问作者Florian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:02:02