Cannot convert value of type 'NSAttributedString.DocumentAttributeKey' to expected dictionary key type 'NSAttributedString.DocumentReadingOptionKey'

时间:2022-06-01 13:01:02

Swift 3切换为Swift 4,原来用于转换html为NSAttributedString的代码报错:

Cannot convert value of type 'NSAttributedString.DocumentAttributeKey' to expected dictionary key type 'NSAttributedString.DocumentReadingOptionKey'

Swift 3代码:

func html2AttributedString() -> NSAttributedString {
    return try! NSAttributedString(
       data: self.data(using: String.Encoding.unicode, allowLossyConversion: true)!, 
       options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
       documentAttributes: nil)
}

在Swift 4转换为NSAttributedString需要使用DocumentType选项:

  • doc:NSAttributedString.DocumentType.docFormat
  • html:NSAttributedString.DocumentType.html
  • plain文本:NSAttributedString.DocumentType.plain
  • 富文本:NSAttributedString.DocumentType.rtf
  • 带有附件的富文本:NSAttributedString.DocumentType.rtfd

所以Swift4对应的代码为:

func html2AttributedString() -> NSAttributedString {
 return try! NSAttributedString(
    data: modifiedFont.data(using: .unicode, allowLossyConversion: true)!,
    options:[.documentType: NSAttributedString.DocumentType.html,
    .characterEncoding: String.Encoding.utf8.rawValue],
    documentAttributes: nil)
}

需要加上

.characterEncoding: String.Encoding.utf8.rawValue

否则可能会导致app崩溃。