Loading...

How to make Color conform to RawRepresentable in Swift in macOS?

question swift macOS
Ram Patra Published on October 29, 2023

For various reasons you may want to convert the Color type to a String. And, below is a relatively cleaner way to do it.

import SwiftUI

extension Color: RawRepresentable {
    
    public init(rawValue: String) {
        guard let data = Data(base64Encoded: rawValue) else {
            self = .gray
            return
        }
        do {
            let color = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSColor.self, from: data) ?? .gray
            self = Color(color)
        } catch {
            self = .gray
        }
    }
    
    public var rawValue: String {
        do {
            let data = try NSKeyedArchiver.archivedData(withRootObject: NSColor(self), requiringSecureCoding: false) as Data
            return data.base64EncodedString()
        } catch {
            return ""
        }
    }
}

You can use it like:

var rawColor: String = Color.blue.rawValue
var someColor: Color = Color(rawValue: rawColor)
Ram Patra Published on October 29, 2023
Image placeholder

Keep reading

If this article was helpful, others might be too

question swift November 17, 2023 How to loop through an array of structs in Swift?

Looping through an array of structs in Swift is straightforward and can be done in several ways depending on what you need to achieve. Here’s how to do it:

question macOS swift August 14, 2020 How to quit or close an app in macOS using Swift?

You can quit or exit an app with:NSApp.terminate(self)

June 7, 2020 How to add Global Key Shortcuts to your macOS app using MASShortcut

Adding Global Keyboard Shortcuts to your macOS app can be a pain as there isn’t a Cocoa API for the same. You would have to rely on the old, most of which are deprecated, Carbon API.