swift - 来自枚举的 Swift 字符串
问题描述
我试图在这里获取文本以读取privacyNotice
存储在Content
枚举扩展名中的文本字符串的内容Chat.Message.Incoming
。以下内容此时无法编译:
private func renderPolicy(
isEnabled: Bool,
resource: ChosenResource<Notice>,
message: Chat.Message.Incoming,
) -> Node<NodeId> {
return Node(
component: Component.Message(
....
text: message.content.privacyNotice.text,
....
)
}
这是扩展:
extension Chat.Message.Incoming {
public enum Content {
case text(message: String, style: Style)
case response(message: String)
case privacyNotice(text: String, resource: ChosenResource<Notice>)
}
}
在控制台中,当我遇到断点并键入时,po message.content
我得到以下信息:
(lldb) po message.content
▿ Content
▿ privacyNotice : 2 elements
- text : "Privacy"
▿ resource : ChosenResource<Notice>
- generator : (Function)
那么如何导航我在输入时得到的错误po message.content.privacyNotice.text
,这是我期望返回Privacy
的,因此使我能够在renderPolicy
函数中输入它:
(lldb) po message.content.privacyNotice.text
error: <EXPR>:3:9: error: enum case 'privacyNotice' cannot be used as an instance member
message.content.privacyNotice.text
~~~~~~~~^~~~~~~
Chat.Message.Incoming.Content.
error: <EXPR>:3:31: error: value of type '(String, ChosenResource<Notice>) -> Chat.Message.Incoming.Content' has no member 'text'
message.content.privacyNotice.text
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^~~~
TIA
解决方案
在您的renderPolicy
函数中,message.content
只是 type Content
,不保证是 case privacyNotice
,也可能是text
or response
,两者都没有text
关联值。
因此,为了访问该关联值,您需要确保它message.content
实际上是大小写privacyNotice
- 您可以使用if case ...
.
private func renderPolicy(
isEnabled: Bool,
resource: ChosenResource<Notice>,
message: Chat.Message.Incoming,
) -> Node<NodeId> {
if case .privacyNotice(text: let text, resource: _) = message.content {
return Node(
component: Component.Message(
....
text: text,
....
)
} else {
// handle the other casese
}
}
推荐阅读
- python - 我怎么能提高我的算法的速度,即使是最轻微的
- python - 如何清除套接字缓冲区?
- css - 覆盖 vuetify 对话框的溢出属性
- vue.js - 为 sweet-alert2 加载 CSS bootstrap-4 主题
- javascript - 如何射击类似于Galaga的导弹?
- javascript - 如何在屏幕之间成功传递参数?
- javascript - 如果名称在列中,则将该列转换为日期格式 Google 表格
- android - 如何在没有 USB 连接的情况下通过 WiFi 调试我的 Android 应用程序?
- auth0 - go lang中的Auth0无效状态参数
- unicode - 您可以在下划线上方键入连字符吗?