eddiekaiger / SwiftyAttributes

A Swifty API for attributed strings

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Convert an array of attributes to a dictionary

scalessec opened this issue · comments

Hey @eddiekaiger, first off thanks for the really useful library -- It's already been a huge timesaver for me.

Maybe I'm overlooking it, but is there a convenient way to go from [Attribute] to [String: Any]?

I keep running into situations like this:

let attributes: [Attribute] = [.font(UIFont.systemFont(ofSize: 15.0)), .textColor(.red)]
UINavigationBar.appearance().titleTextAttributes = ??

An extension of [Attribute] would be a pretty awesome way to handle this (if it's even possible). Thoughts?

Hey @scalessec, thanks for pointing that out. It seems I'm the one overlooking things here -- that's a great suggestion and should definitely be built in! This can't be done currently in a concise way, but I'll make sure to add this capability in v3.1.0 that I'm wrapping up.

If you copy the code from here (that variable isn't public unfortunately), you can write a complete solution in the meantime doing something like this:

extension Sequence where Self.Iterator.Element == Attribute {

    var attributeDictionary: [String: Any] {

        return reduce([String: Any]()) {
            var dict = $0

            let value: Any
            switch $1 {
            case .ligatures(let ligatures): value = ligatures.rawValue
            case .strikethroughStyle(let style): value = NSNumber(value: style.rawValue)
            case .textEffect(let effect): value = effect.rawValue
            case .underlineStyle(let style): value = NSNumber(value: style.rawValue)
            case .writingDirections(let directions): value = directions.map { $0.rawValue }
            default: value = $1.value
            }

            dict[$1.keyName] = value
            return dict
        }

    }

}

I'm going to keep this issue open until the solution gets implemented.

Brilliant, thanks!

This is now live on CocoaPods with version 3.1.0. Cheers!