Home > Enterprise >  What does Array and ... does here?
What does Array and ... does here?

Time:09-20

I have this line here, I can not understand the purpose, and the sytacs.

instances = Array(Array(instance.enumerated())[prefixItems.count...])

  1. What does ...
  2. What does [prefixItems.count...] when creating an Array?
  3. How instances can be assigned to a type like: [(Int, Any)].

this is the whole statement, it is syntactically valid:

  let instances: [(Int, Any)]
  if let prefixItems = schema["prefixItems"]?.array {
    guard instance.count > prefixItems.count else {
      return AnySequence(EmptyCollection())
    }
    instances = Array(Array(instance.enumerated())[prefixItems.count...])
  } else {
    instances = Array(instance.enumerated())
  }

but for some reason I need convert Any to DataToValidate, like:

  let instances: [(Int, DataToValidate)]

and then I got error:

Cannot assign value of type 'Array<EnumeratedSequence<(JSONArray)>.Element>' (aka 'Array<(offset: Int, element: JSONValue)>') to type '[(Int, DataToValidate)]'

CodePudding user response:

  1. The x... is a one-sided range from x to "as far as possible", i.e., to the end of the array in case of subscripting, as done here.

  2. Array(instance.enumerated()) initializes an array from the enumerated sequence instance, i.e., [(Int, Any)]. The subscript [prefixItems.count...] takes the elements from that array starting from the index prefixItems.count and continuing to the end. The outer Array initializes an array of that sequence.

  3. The types of everything involved above (in practice some will have more specific actual types, but they conform to these):

    • instance – some Sequence, but we can consider it [Any]
    • instance.enumerated()Sequence<(Int, Any)>
    • Array(instance.enumerated())[(Int, Any)]
    • Array(instance.enumerated())[prefixItems.count...]Sequence<(Int, Any>)>
    • Array(Array(instance.enumerated())[prefixItems.count...])[(Int, Any)]

P. S. As pointed out in comments, note that the intermediate array and subscripting is unnecessary, and the same outcome can be achieved with Array(instance.enumerated().dropFirst(prefixItems.count)). This also makes the guard unnecessary.

  • Related