swift - Subscript Syntax to append values in array -
in swift programming language book explicitly states:
you can't use subscript syntax append new item end of array
the example provided in book states if replacement set of values has different length range replacing fine. example:
var shoppinglist = ["eggs", "milk", "chocolate"] shoppinglist[0...2] = ["bananas", "apples"] // shoppinglist = ["bananas", "apples"]
which makes sense because replacing 3 values values of banana , apple. however, if did instead:
var shoppinglist = ["eggs", "milk", "chocolate"] shoppinglist[0...2] = ["bananas", "apples", "sausage", "pear"] // shoppinglist = ["bananas", "apples", "sausage", "pear"]
i thought not allowed use subscript syntax append new item end of array, seems loophole in language. can explain me why happens and/if valid behaviour or bug? thanks!
when book says “you can’t use subscript syntax append new item end of array”, means is, “the way array.subscript (index: int) -> t
has been implemented, can’t use append new item end of array”.
subscript
bit of syntactic sugar function propertyish qualities takes arguments (in case index
) , either gets or sets value (in case t
). function, can whatever want. set value @ index
, or fire nuclear missiles if wrote way.
as happens, array
defines second overload subscript
operates on ranges, , does have extending capabilities. book referring more conventional 1 takes single index.
to demonstrate, here’s extension array
defines version of subscript, time 1 if name index extend:
, extend array new value desired index:
extension array { // add new subscript named argument subscript (extending index: int) -> t { { return self[index] } set(newvalue) { if index < self.endindex { self[index] } else { let extendby = index + 1 - self.endindex self.extend(repeat(count: extendby, repeatedvalue: newvalue)) } } } } var = [1,2,3] a[extending: 5] = 100 // [1, 2, 3, 100, 100, 100]
Comments
Post a Comment