[英]SwiftUI: Custom String Type
I've just started learning SwiftUI, so I'm very new to framework and know very little about the Swift language in general. 我刚刚开始学习SwiftUI,所以我对框架非常陌生,并且对Swift语言总体了解甚少。 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"
). 我有一个
@State
变量,它可以是三个字符串( "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
. 问题是,我想强制执行此变量以使其符合“ stricter”类型,而不是简单地将其设置为
String
。
Something akin to this maybe... (I realise this isn't valid, but I'm coming from a TypeScript world so please forgive me) 可能与此类似...(我意识到这是无效的,但我来自TypeScript世界,请原谅我)
type Mode = "OFF" | "ON" | "ONCE"
@State private var mode: Mode = "OFF"
Any help would be appreciated. 任何帮助,将不胜感激。 Thanks in advance!
提前致谢!
You should use an enum
你应该使用一个
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 Swift中的枚举功能非常强大,请在此处查看完整指南: 枚举
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.