Kodeco Forums

Implementing Custom Subscripts in Swift

Learn how to extend your own types with subscripts, allowing you to index into them with simple syntax just like native arrays and dictionaries.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/1114-implementing-custom-subscripts-in-swift

Awesome tutorial! Very helpful and informative indeed. I have one question though, I was following with no problems up until the second subscript implementation.

subscript(x: Int, y: Int) -> Square {
  get {
    return self[(x: x, y: y)]
  }
  set {
    self[(x: x, y: y)] = newValue
  }
}

I don’t quite understand how does the self[(x: x, y: y)] part works, in this case how does Swift knows we are referring to the squares array?

If someone could elaborate on this it would be awesome, thank you!

Swift knows we are referring to the squares array, because you defined a subscript that takes a coordinate above. You are using the setter of the first subscript in this case.

This tutorial is more than six months old so questions regarding it are no longer supported for the moment. We will update it as soon as possible. Thank you! :]