Swift 3 NSAttributedString multiple attributes

The main issue is that you are passing an array [attr.. , attr...] rather than one dictionary.

You need to merge the two dictionaries into one

let attributeFontSaySomething : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 12.0)]
let attributeColorSaySomething : [String : Any] = [NSForegroundColorAttributeName : UIColor.blue]

var attributes = attributeFontSaySomething
for (key, value) in attributeColorSaySomething {
    attributes(value, forKey: key)
}

let attStringSaySomething = NSAttributedString(string: "Say something", attributes: attributes)

However it might be easier to create the dictionary literally:

let attributes : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 12.0), NSForegroundColorAttributeName : UIColor.blue]

Just create a single dictionary with both sets of attributes:

let attributes: [String:AnyObject] = 
  [NSFontAttributeName : UIFont.fontSaySomething(), 
  NSForegroundColorAttributeName : UIColor.blue]

And then use the dictionary with both key/value pairs when creating your attributed string.

There's no built-in mechanism in Swift for combining dictionaries, but you could add an override of the + operator if you wanted to be able to add dictionaries together (You'd have to work out what to do if both dictionaries contained the same key however.)


Use like this:

let attStringSaySomething = NSAttributedString.init(string: "Hello", attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 16), NSForegroundColorAttributeName:UIColor.black])