0

I've just started learning SwiftUI, so I'm very new to framework and know very little about the Swift language in general. I'm trying to figure out how to define a custom type.

I've got a @State variable that can be one of three strings ("OFF", "ON", "ONCE").

This is what I have so far:

@State private var mode: String = "OFF"

The problem is, I would like to enforce this variable to conform to a "stricter" type instead of simply setting it to String.

Something akin to this maybe... (I realise this isn't valid, but I'm coming from a TypeScript world so please forgive me)

type Mode = "OFF" | "ON" | "ONCE"

@State private var mode: Mode = "OFF"

Any help would be appreciated. Thanks in advance!

1
  • 3
    Use an enum instead of string Commented Jun 11, 2019 at 15:07

1 Answer 1

3

You should use an enum

enum Mode: String {
    case on = "ON"
    case off = "OFF"
    case once = "ONCE"
}

Enum in Swift are really powerful, check the complete guide here: Enumerations

Sign up to request clarification or add additional context in comments.

2 Comments

You're defining the raw value of each of the cases with `= "ON", right?
Yes, but of course the raw value could be whatever you need

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.