Loading...

How to make Color conform to RawRepresentable in SwiftUI 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)
Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on October 29, 2023
Image placeholder

Keep reading

If this article was helpful, others might be too

question swiftui swift September 8, 2024 How to loop through an enum in SwiftUI?

In SwiftUI, looping through an enum is not directly possible without some extra work because enums in Swift don’t inherently support iteration. However, you can achieve this by making the enum CaseIterable, which automatically provides a collection of all cases in the enum.

question swiftui swift September 2, 2024 Combine in SwiftUI and how you can rewrite the same code using async await

Combine is Apple’s declarative framework for handling asynchronous events and data streams in Swift. Introduced in SwiftUI and iOS 13, Combine leverages reactive programming principles, allowing developers to process values over time and manage complex asynchronous workflows with clarity and efficiency.

question macOS swift August 6, 2020 How to keep an app's window always on top of others in Swift?

Before launching the window, just use the appropriate window level, and you’re done.