Add associated values to NSAttributedString.Key cases
Hey everyone, I was working with
NSAttributedString recently and noticed the following bothering me, would like to have your thought on it.
Currently, in order to use NSAttributedString APIs, we usually have codes like this one:
let attributes:[NSAttributedString.Key:Any] = [ .font : UIFont.systemFont(ofSize: 100), .backgroundColor : UIColor.yellow, .strokeWidth : -2, .strokeColor : UIColor.black, .foregroundColor : UIColor.red, ] let attrString = NSAttributedString(string: "A string", attributes: attributes)
We are using
Any which is not cool since we know the expected value for each possible
With enum and associated values in Swift, wouldn't make more sense to write the previous code like below?
let attributes:[StringAttribute] = [ .font(.systemFont(ofSize: 100)), .backgroundColor(.yellow), .strokeWidth(-2), .strokeColor(.black), .foregroundColor(.white) ] let attrString = NSAttributedString(string: "A string", attributes: attributes)
The associated value will always have the expected value by that attribute.
We can leverage type inference to make the code smaller when using a static/class var/func.
Apps that strongly rely on attributed strings to set its theme
Swift bridging overhead
The implementation can add some overhead to bridge the enum with this associated value
Here's a sample project I implemented a little wrapper to demonstrate this idea.