3

I am using below code in my project. After update to swift 4 I am getting errors. How can I fix it?

Code:

let returnString : NSAttributedString

   if styleList.count > 0
   {
       var attrs = [String:AnyObject]()
       attrs[NSAttributedStringKey.font] = codeFont
       for style in styleList
       {
         if let themeStyle = themeDict[style]
         {
             for (attrName, attrValue) in themeStyle
             {
                 attrs.updateValue(attrValue, forKey: attrName)
             }
         }
     }

     returnString = NSAttributedString(string: string, attributes:attrs )
 }

Here are Errors:


Cannot subscript a value of type '[String : AnyObject]' with an index of type 'NSAttributedStringKey'


Cannot convert value of type '[String : AnyObject]' to expected argument type '[NSAttributedStringKey : Any]?'

Krunal
  • 77,632
  • 48
  • 245
  • 261
  • 2
    The attributes should be of type [NSAttributedStringKey : Any], not [String:AnyObject]. – Ramy Al Zuhouri Oct 13 '17 at 13:03
  • To give an explanation: `NSAttributedString` is not a subclass of `NSString` as one might think. – Amin Negm-Awad Oct 13 '17 at 13:21
  • @RamyAlZuhouri fine working , thanks –  Oct 13 '17 at 13:30
  • And don't check `if styleList.count > 0` test if it is not empty `!styleList.isEmpty` – Leo Dabus Oct 13 '17 at 13:31
  • And if you define your attrs type `[NSAttributedStringKey: Any]` as @RamyAlZuhouri said there is no need to use `attrs[NSAttributedStringKey.font] = codeFont` just pass the case `attrs[.font] = codeFont` – Leo Dabus Oct 13 '17 at 13:34
  • This was explained in my answer to your [previous question](https://stackoverflow.com/questions/46719761/cannot-convert-value-of-type-string-date-to-expected-argument-type-filea). – rmaddy Oct 13 '17 at 14:58

1 Answers1

9

In swift 4 - NSAttributedString representation is completely changed.

Replace your attribute dictionary attrs type [String:AnyObject]with [NSAttributedStringKey:Any]

Try this:

let returnString : NSAttributedString

   if styleList.count > 0
   {
       var attrs = [NSAttributedStringKey:Any]()  // Updated line 
       attrs[NSAttributedStringKey.font] = codeFont
       for style in styleList
       {
         if let themeStyle = themeDict[style]
         {
             for (attrName, attrValue) in themeStyle
             {
                 attrs.updateValue(attrValue, forKey: attrName)
             }
         }
     }

     returnString = NSAttributedString(string: string, attributes:attrs )
 }

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

Krunal
  • 77,632
  • 48
  • 245
  • 261