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 swiftui swift September 30, 2023 How to open the Settings view in a SwiftUI app on macOS 14.0 (Sonoma)?

In macOS 14.0 (Sonoma), Apple removed support for NSApp.sendAction to open the Settings view in your SwiftUI app. You now have to use SettingsLink like below:

question swift November 17, 2023 How do get the string value of an enum in Swift?

In Swift, to get the string value of an enum, you typically have a couple of approaches depending on the enum’s definition. Let’s go through them:

question swift August 9, 2020 How to iterate an array in reverse in Swift?

From Swift 5.0, you can use any of the following approaches to iterate an array in reverse.