[swift-evolution] constant var

Joe Groff jgroff at apple.com
Thu Dec 14 11:39:18 CST 2017



> On Dec 14, 2017, at 12:51 AM, Inder Kumar Rathore . <rathore619 at gmail.com> wrote:
> 
> class MyClass {
>   private var myDict = [String : String]()
>   
>   func addMemebr() {
>     self.myDict["key"] = "value" // Ok for me
>   }
>   
>   func anotherFunc() {
>     self.myDict = [String : String]() // Not okay for me, I don't want any code to do this within the class
>   }
> }

If you want code to be able to insert, but not delete from or otherwise freely change, the dictionary value, you could provide a wrapper type for myDict that provides a restricted mutation API:

struct InsertOnlyDictionary {
  private(set) var value = [String: String]()

  mutating func insert(_ k: String, _ v: String) {
    value[k] = v
  }
}

// Code outside of InsertOnlyDictionary can read its `value`, but can only modify it by its `insert` API
class MyClass {
  private var myDict = InsertOnlyDictionary()

  func addMember() {
    self.myDict.insert("key", "value")
  }
}

-Joe

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171214/94756475/attachment.html>


More information about the swift-evolution mailing list