Swift无法通过下标分配:“ peerDeviceSettings”是仅获取属性”

时间:2019-07-25 09:18:49

标签: ios swift dictionary

我的课堂上有以下声明:

var peerDevice: [String: Any]? 

private var peerDeviceSettings:[String:Any]? {
    get {
        if let settings = peerDevice?["settings"] as? [String:Any] {
            return settings
        }

        return nil
    }
}

现在的问题是,是否要更改peerDeviceSettings,例如:

 fileprivate func set(_ value: Any?, forKey key: Key) {
    if peerDeviceSettings != nil {
        peerDeviceSettings?[key.rawValue] = value
    } 
 }

我收到错误

 Cannot assign through subscript: 'peerDeviceSettings' is a get-only property

要点是如何重新构建此东西而不创建新的可变变量peerDeviceSettings?

4 个答案:

答案 0 :(得分:1)

只需将set (setter)添加到属性中并在那里进行处理。

private var peerDeviceSettings:[String:Any]? {
    get {
        if let settings = peerDevice?["settings"] as? [String:Any] {
            return settings
        }

        return nil
    }
    set {

    }
}

答案 1 :(得分:1)

您的代码似乎很好,因为您正在创建到嵌套settings字典的链接(听起来合理)

只需添加二传手:

private var peerDeviceSettings: [String: Any]? {
    get {
        if let settings = peerDevice?["settings"] as? [String:Any] {
            return settings
        }

        return nil
    }
    set { 
      if peerDevice == nil {
        peerDevice = [:] // if it's desired behavior
      }
      peerDevice?["settings"] = newValue 
    }

}

我还建议您摆脱peerDevice中的可选性,只需将其初始化为空值(如果它符合您的逻辑)

答案 2 :(得分:1)

您看到此错误,因为您仅声明了属性的getter,还添加了setter

    private var peerDeviceSettings:[String:Any]? {
    get {
        if let settings = peerDevice?["settings"] as? [String:Any] {
            return settings
        }

        return nil
    }
    set {
        peerDevice?["settings"] = newValue
    }
}

更新:显示在特定情况下必须如何显示

答案 3 :(得分:1)

您需要二传手

private var peerDeviceSettings:[String:Any]? {
    get {
        return  peerDevice?["settings"] as? [String:Any]
    }

    set {
        peerDevice?["settings"] = newValue
    }
}