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

Swift 4.1(Xcode 9.3.1)中Type 'String' has no member 'documentType'错误求助

搞定Swift 4.1里的「Type 'String' has no member 'documentType'」错误

嘿,这个问题我在Swift 4.1(搭配Xcode 9.3.1)的项目里碰到过好多次,本质是版本差异导致的枚举键写法问题,我来给你捋清楚怎么解决:

问题根源

在Swift 4.2及更高版本(对应Xcode 10+)里,Apple简化了NSAttributedString初始化时的选项键写法,你可以直接用.documentType;但在Swift 4.1里,编译器还不支持这种简化写法,它会误以为你在访问String类型的documentType成员,自然就抛出错误了。

修正后的完整代码

do {
    let modifiedFont = NSString(format:"<span style=\"font-family: '-apple-system', 'HelveticaNeue'; font-size: 16\">%@</span>" as NSString, string) as String
    let data = modifiedFont.data(using: String.Encoding.utf8, allowLossyConversion: true)
    if let d = data {
        // 关键修改:用完整的枚举类型指定选项键
        let str = try NSAttributedString(data: d, 
                                        options: [NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html], 
                                        documentAttributes: nil)
        return str
    }
} catch {
    // 补充错误处理,避免崩溃
    print("富文本解析失败:\(error.localizedDescription)")
    return NSAttributedString(string: string)
}

额外提示

原代码里没有catch块,建议一定要加上——如果HTML格式有误或者解析失败,程序会直接崩溃,添加错误处理能让你的代码更健壮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:47:23