Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 attributedString get typing attributes

I am trying to create AttributedString and add the attributes from

typingAttributes(from textView)

The problem is that

.typingAttributes

return

[String, Any]

and

NSAttributedString(string:.. , attributes:[])

needs

[NSAttributedStringKey: Any]

My code:

NSAttributedString(string: "test123", attributes: self.textView.typingAttributes)

I don't want to create for in cycle to go through all keys and change them to

NSAttributedStringKey
like image 658
Altimir Antonov Avatar asked Sep 28 '17 13:09

Altimir Antonov


1 Answers

You can map the [String: Any] dictionary to a [NSAttributedStringKey: Any] dictionary with

let typingAttributes = Dictionary(uniqueKeysWithValues: self.textView.typingAttributes.map {
    key, value in (NSAttributedStringKey(key), value)
})

let text = NSAttributedString(string: "test123", attributes: typingAttributes)

Here is a possible extension method for that purpose, it is restricted to dictionaries with string keys:

extension Dictionary where Key == String {

    func toAttributedStringKeys() -> [NSAttributedStringKey: Value] {
        return Dictionary<NSAttributedStringKey, Value>(uniqueKeysWithValues: map {
            key, value in (NSAttributedStringKey(key), value)
        })
    }
}
like image 138
Martin R Avatar answered Oct 16 '22 17:10

Martin R