Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have just updated to Xcode 9 and converted my app from swift 3 to swift 4 and get this errors. how i can fix this?

 func displayText() {
    do {
        if url.pathExtension.lowercased() != "rtf" {
            let fileContent = try String(contentsOf: url)
            text.text = fileContent
        } else { // Is RTF file
            let attributedString = try NSAttributedString(url: url, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil)
            text.attributedText = attributedString
            text.isEditable = false
        }
    }

And get this Error

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


1 Answers

In swift 4 - NSAttributedString representation is completely changed.

Replace your attribute dictionary key and value [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType]with [NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.rtf]

Try this:

func displayText() {
    do {
        if url.pathExtension.lowercased() != "rtf" {
            let fileContent = try String(contentsOf: url)
            text.text = fileContent
        } else { // Is RTF file
            let attributedString = try NSAttributedString(url: url, options: [NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.rtf], documentAttributes: nil)
            text.attributedText = attributedString
            text.isEditable = false
        }
    }
}

Here is note from Apple: NSAttributedString - Creating an NSAttributedString Object

like image 149
Krunal Avatar answered Dec 02 '25 05:12

Krunal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!