eddiekaiger / SwiftyAttributes

A Swifty API for attributed strings
MIT License
1.64k stars 83 forks source link

Crashes with custom NSAttributedStringKey #25

Closed scalessec closed 6 years ago

scalessec commented 6 years ago

When working with NSAttributedStrings that use custom NSAttributedStringKey values, SwiftyAttributes crashes whenever attributes are accessed.

Here's one way to reproduce:

let attributedString = NSMutableAttributedString(string: "hello world")
attributedString.setAttributes([NSAttributedStringKey("crash"): "bang"], range: NSRange(..<attributedString.length))
attributedString.enumerateSwiftyAttributes(in: 0..<attributedString.length) { attributes, _, _ in
    debugPrint(attributes)
}

I realize that type-safety for a finite number of Foundation values is part of SwiftyAttributes's appeal, but I also think this crash should be handled by the library due to the existence of NSAttributedStringKey(string:).

I haven't given too much thought into how I think this could be handled, but perhaps something like: .custom([String: Any]) is an appropriate solution for any NSAttributedStringKey values that can't be constructed via NSAttributedStringKey(rawValue:).

FWIW, this came up due to some work I'm doing with markdown rendering, where we're storing the URL for links in a custom attribute as part of the attributed string.

eddiekaiger commented 6 years ago

Interesting, I've never considered custom string keys. I like the idea of a .custom attribute, although I feel like .custom(String, Any) would make more sense to ensure a one-to-one mapping of attribute to Attribute. Started working on it already!

eddiekaiger commented 6 years ago

@scalessec Just opened #26, feel free to give feedback!

eddiekaiger commented 6 years ago

Fixed in v4.2.0! Thanks for calling this out.