swift中, enum CommentType :String { case articleType = "article" case pyqType = "pyq" } 枚举,这时候有个变量 target = "article",让他去匹配枚举的字符串,并返回articleType 这样子的枚举值,并用另外一个变量targetType去接收这个 枚举值,怎么写
时间: 2024-03-28 22:41:35 浏览: 13
你可以这样写:
```
enum CommentType: String {
case articleType = "article"
case pyqType = "pyq"
}
let target = "article"
if let targetType = CommentType(rawValue: target) {
// targetType is now an instance of CommentType
print(targetType) // prints "articleType"
} else {
// target is not a valid value for CommentType
print("Invalid value for CommentType")
}
```
在这个例子中,我们首先定义了一个枚举 `CommentType`,它有两个成员,分别对应字符串值 `article` 和 `pyq`。然后我们定义了一个字符串变量 `target`,它的值是 `"article"`。接着我们使用 `rawValue` 方法将 `target` 转换成 `CommentType` 枚举类型,如果转换成功,那么 `targetType` 变量会接收到对应的枚举值,也就是 `articleType`;否则,`target` 不是一个有效的枚举值。
相关问题
enum StgType : int { StgInvalid = 0, StgStorage = 1, StgStream = 2, StgLockbytes = 3, StgProperty = 4, StgRoot = 5 } enum StgColor : int { Red = 0, Black = 1 }这段代码是什么意思c#
这段代码是C#中定义了两个枚举类型,分别是StgType和StgColor。
StgType枚举类型定义了一些存储类型的常量,包括:
- StgInvalid:表示无效的存储类型,值为0;
- StgStorage:表示存储类型为存储对象,值为1;
- StgStream:表示存储类型为数据流,值为2;
- StgLockbytes:表示存储类型为锁定字节,值为3;
- StgProperty:表示存储类型为属性,值为4;
- StgRoot:表示存储类型为根,值为5。
StgColor枚举类型定义了一些颜色的常量,包括:
- Red:表示红色,值为0;
- Black:表示黑色,值为1。
这些枚举类型的定义可以在代码中方便地使用,比如可以通过StgType枚举类型的常量来表示某个存储对象的类型,或者通过StgColor枚举类型的常量来表示某个元素的颜色。
直接判断一个string类型是否在枚举类enum class中
可以使用static_cast<int>将枚举类型转换为整型,然后使用std::underlying_type获取底层类型,最后使用std::find判断string是否在枚举类中。示例代码如下:
```c++
#include <iostream>
#include <string>
#include <algorithm>
#include <type_traits>
enum class Colors {
RED,
GREEN,
BLUE
};
int main() {
std::string color = "GREEN";
auto colorValue = static_cast<std::underlying_type_t<Colors>>(Colors::GREEN);
auto enumValues = { static_cast<std::underlying_type_t<Colors>>(Colors::RED),
static_cast<std::underlying_type_t<Colors>>(Colors::GREEN),
static_cast<std::underlying_type_t<Colors>>(Colors::BLUE) };
auto result = std::find(enumValues.begin(), enumValues.end(), colorValue);
if (result != enumValues.end()) {
std::cout << color << " is in Colors enum class" << std::endl;
}
else {
std::cout << color << " is not in Colors enum class" << std::endl;
}
return 0;
}
```
输出结果为:
```
GREEN is in Colors enum class
```