简体   繁体   中英

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

I have this declaration in my class:

var peerDevice: [String: Any]? 

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

        return nil
    }
}

Now the problem is if I wish to change peerDeviceSettings, such as this:

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

I get an error

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

The point is how do I rearchitect this thing without creating a new mutable variable peerDeviceSettings?

Just add set (setter) to the property and handle it there.

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

        return nil
    }
    set {

    }
}

your code seems to be fine, since you're creating links to the nested settings dictionary (sounds reasonably)

just add setter:

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 
    }

}

I'd also suggest getting rid of optionality in peerDevice , just initialize it with empty value (if it feets your logic)

You see this error because you declared only getter for your property, you have also add setter

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

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

UPDATE: to show how it must be in this certain case

You need a setter

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM