Hacker News new | past | comments | ask | show | jobs | submit login

Attributed Strings got better type information in Swift 4 (it got what Notification keys got in Swift 3), but like notifications it's an open-ended API so I don't know what else you can do...

You can't use an enum for the keys because it supports custom attributes (at least you can't without exposing a `.custom(name: String)` case, which would defeat the purpose). And the values can be different types (enums for underline styles, URLs for links, [NS|UI]Color for foreground colors, etc.). I think the `NSAttributedStringKey` box type is a good compromise.

Maybe I'm biased (the Cocoa text system is one of my favorite APIs, and NSAttributedString is at the top), but I'm really happy with the state of attributed strings in Swift 4 myself.




True, but that's exactly the kind of change to the API required to make it more compile-safe. I still managed to crash this API by not providing a .rawValue somewhere. I don't think applications need to crash on key-value errors.

An enum wouldn't be so bad if it also would use the associated value. Would make it impossible to set the wrong value at least.


Ahh right, NSUnderlineStyle... I totally thought that was improved in Swift 4, what a bummer. I have some unit tests in my apps that make sure I'm setting the .rawValue instead of the enum case itself, because that one does suck. I'm gonna file a bug.


Yup that was exactly the one!


I see Swift supports generics so could they let you define subclasses of string enums that support custom string values?


Swift also supports associated values with enum cases, so you could do something like this[0] and get type-safety. Now you could only associate a URL type with a link attribute, or an NSColor type with a foregroundColor attribute, etc.

However, you can't (at least currently) add new cases to someone else's enum (the way you can add methods). So if I decided I wanted my own custom text attributes (which isn't uncommon), we're back to type-unsafe land. We'd need the original enum to have an extra attribute case, like this[1].

[0]https://pastebin.com/L1xPcueu [1]https://pastebin.com/h8Rp3Ajy




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: