简体   繁体   English

SwiftUI:自定义字符串类型

[英]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.

相关问题 参数类型问题(字符串)-&gt; () - SwiftUI - Problem with argument type (String) -> () - SwiftUI 添加自定义 fonts 作为字体类型 SwiftUI 的扩展 - Adding custom fonts as an extension to the Font type SwiftUI 将自定义类型转换为 String - Transfer custom type to String 无法将“JSON”类型的值转换为预期的参数类型“字符串?” SwiftUI - Cannot convert value of type 'JSON' to expected argument type 'String?' SwiftUI 无法将“图像”类型的值转换为 SwiftUI 中的预期参数类型“字符串” - Cannot convert value of type 'Image' to expected argument type 'String' in SwiftUI SwiftUI - 无法将类型“[String]”的值分配给类型“[SignUpViewModel.ErrorMessage]” - SwiftUI - Cannot assign value of type '[String]' to type '[SignUpViewModel.ErrorMessage]' 转换已发布<String> .Publisher&#39; 到指定类型 &#39;String&#39; / SwiftUI / Xcode - Convert Published<String>.Publisher' to specified type 'String' / SwiftUI / Xcode 是否可以在 SwiftUI 中使用带有自定义字体的动态字体大小? - Is it possible to use dynamic type sizes with a custom font in SwiftUI? 如何指定将包含 SwiftUI 自定义视图的数组的类型信息 - How to specify the type information of an array that would hold SwiftUI custom views SwiftUI - Firebase:“String”类型的值没有成员“documentID” - SwiftUI - Firebase: Value of type 'String' has no member 'documentID'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM