【问题标题】:Swift - Nested DictionariesSwift - 嵌套字典
【发布时间】:2019-05-02 06:29:22
【问题描述】:

我需要在代码中重新创建下面的嵌套字典,但即使我发现了很多关于该主题的问题,我也被卡住了。

这是我需要重新创建的字典,但我被困在“动作”字符串上。

这是我做的

这是我的字典

var buttonactions: [String:[[String:[String:String]]]] = [:]

这就是我更新测试值的方式,“标记”是我的类,它存储我的按钮操作

  marker.buttonactions.updateValue([["Action" : ["array linked of buttons" : "actionKey"]]], forKey: "button actions array")

我有点困惑如何将“动作”设置为字符串和“按钮数组链接”

任何帮助将非常感谢。

【问题讨论】:

    标签: arrays swift xcode dictionary nested


    【解决方案1】:

    我认为字典结构应该是

    var buttonActions : [String: [String: [String:Any]]] = [:]
    let array_linked_of_buttons = ["linked button UU":"22308345y1p245", "linked button cat...":"", "linked button":"ATT TRANS"]
    let item0Dict: [String:Any] = ["action": "ON_DOWN_SET_UP", "array linked of buttons":array_linked_of_buttons]
    let button_actions_array = ["button action array" : item0Dict]
    buttonActions.updateValue(button_actions_array, forKey: "button actions")
    
    print(buttonActions)
    

    【讨论】:

    • 谢谢!这在操场上有效,但我将如何对其进行编码和解码,以便可以保存在 plist 中?我收到以下错误'类型'标记'不符合协议'可解码''错误是由字典中的'任何'引起的
    • 我找到了这篇文章medium.com/@scotthoyt/…
    【解决方案2】:
    protocol ButtonActionDictValue {}
    
    extension String: ButtonActionDictValue {}
    
    extension Array: ButtonActionDictValue where Element == [String: String] {}
    
    typealias ButtonAction = [String: ButtonActionDictValue]
    
    let buttonActions: [ButtonAction] = [
        [ "action": "ON_DOWN_SET_UP"
        , "array linked of buttons": [
                [ "linked button UU": "22307"
                , "linked button cat": ""
                ]
            ]
        ]
    ]
    

    【讨论】:

    • 嗨,Nandiin,请您进一步解释一下。谢谢!
    • 当然。据我了解,您的问题是在字典的“值”字段中允许两种或更多不同的类型。在这种情况下,String 对应于 action 键,String[] 对应于 array linked of buttons 键。为此,我声明了一个名为ButtonActionDictValue 的空协议,然后扩展了StringString[] 以符合该协议。那么预期的字典将是[String: ButtonActionDictValue] 类型。您可以进一步参考我对类似问题的另一个答案(发布在下面)。我希望我能正确理解您的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 2017-01-15
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    • 2015-10-03
    • 2016-07-10
    相关资源
    最近更新 更多