Enum of structs in Swift

So I want to store color setup locally, but it would be better if I only save a String value. Then use this string to get the corresponding value. Below is my result:

// MyColor.swift
class MyColor {
private init() {}
static let primary = Co…


This content originally appeared on DEV Community and was authored by Arno Solo

So I want to store color setup locally, but it would be better if I only save a String value. Then use this string to get the corresponding value. Below is my result:

// MyColor.swift
class MyColor {
    private init() {}
    static let primary = Color("primary")
    static let onPrimary = Color("onPrimary")
    static let secondary = Color("secondary")
    static let onSecondary = Color("onSecondary")
}

struct ColorPair {
    let bg: Color
    let onBg: Color
}

enum ColorPairType: String {
    case primary = "primary"
    case secondary = "secondary"

    func value() -> ColorPair {
        switch self {
        case .primary:
            return ColorPair(bg: MyColor.primary, onBg: MyColor.onPrimary)
        case .secondary:
            return ColorPair(bg: MyColor.secondary, onBg: MyColor.onSecondary)
    }
}
// DemoView.swift

@State var currentColor: ColorPairType = .secondary

Text("hello")
    .foregroundColor(currentColor.value().onBg)

If you find this article useful, maybe you can buy my calculator for $0.99? It's a calculator that can change the layout of the keys. This way you can only keep the keys that are useful to you. -> App Store


This content originally appeared on DEV Community and was authored by Arno Solo


Print Share Comment Cite Upload Translate Updates
APA

Arno Solo | Sciencx (2023-04-05T12:49:09+00:00) Enum of structs in Swift. Retrieved from https://www.scien.cx/2023/04/05/enum-of-structs-in-swift/

MLA
" » Enum of structs in Swift." Arno Solo | Sciencx - Wednesday April 5, 2023, https://www.scien.cx/2023/04/05/enum-of-structs-in-swift/
HARVARD
Arno Solo | Sciencx Wednesday April 5, 2023 » Enum of structs in Swift., viewed ,<https://www.scien.cx/2023/04/05/enum-of-structs-in-swift/>
VANCOUVER
Arno Solo | Sciencx - » Enum of structs in Swift. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/04/05/enum-of-structs-in-swift/
CHICAGO
" » Enum of structs in Swift." Arno Solo | Sciencx - Accessed . https://www.scien.cx/2023/04/05/enum-of-structs-in-swift/
IEEE
" » Enum of structs in Swift." Arno Solo | Sciencx [Online]. Available: https://www.scien.cx/2023/04/05/enum-of-structs-in-swift/. [Accessed: ]
rf:citation
» Enum of structs in Swift | Arno Solo | Sciencx | https://www.scien.cx/2023/04/05/enum-of-structs-in-swift/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.