首页 > 解决方案 > 来自枚举的 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

标签: swiftstringenums

解决方案


在您的renderPolicy函数中,message.content只是 type Content,不保证是 case privacyNotice,也可能是textor 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
    }

}

推荐阅读