title: computed setter for a subscript of an array in Swift
body: <p>To keep it short, what I want to achieve is for example:</p>
  
  <pre><code>var actions: [String]{
      get{
          if (_actions==nil){
              _actions = []
          }
          return _actions!
      }
      set{
          _actions = newValue
      }
      subscript(index:Int) -&gt; String{
        set {
           assert(index&lt;_actions.count &amp;&amp; index&gt;=0, "Index out of range")
           _actions[index] = newValue
        }
      }
  }
  </code></pre>
  
  <p>I know subscript isn't an accessor for array, but then what is the most convinient alternative to do just that?</p>
  
  <p>I truly appreciate for succinct answers if possible! Thank you very much!</p>
  
  <p>Edit:</p>
  
  <p>To extend my explanation for @jrturton, </p>
  
  <p>What I am trying to achieve is whenever actions[i] is set to a newValue, I would like to do some extra computations, such as repositioning actions[i]'s respective subview. </p>
  
  <p>But if i say <code>actions[3] = "randomMethod"</code>, the computed setter for the entire array will get called. Right? So I'd like to find a way so that when <code>actions[3]</code> is set to a newValue, a function <code>repositionView(3)</code> can get called, for example.</p>
  
  <p>I know other ways to do it, but my question simply askes if there is a more convinient way, like the example above: a computed setter, to do what I want?</p>
  
  <p>Edit 2:</p>
  
  <p>To show @Vatsal Manot what I truly mean, I removed getter for subscript, and here is a complete example.swift(which wont run due to error):</p>
  
  <pre><code>import UIKit
  import Foundation
  
  class DWActionsSubmenu: UIView{
      var actions: [DWAction]{
          get{
              if (_actions==nil){
                  _actions = []
              }
              return _actions!
          }
          set{
              _actions = newValue
          }
          subscript(index:Int) -&gt; DWAction{
              set {
                  assert(index&lt;_actions.count &amp;&amp; index&gt;=0, "Index out of range")
                  _actions[index] = newValue
                  a()
              }
          }
      }
  
      var _actions: [DWAction]?
  
      init(actions:[DWAction]?){
          super.init()
          _actions = actions
      }
  
      required init(coder aDecoder: NSCoder) {
          super.init(coder:aDecoder)
      }
  
      func a(){
  
      }
  }
  </code></pre>