I have this line here, I can not understand the purpose, and the sytacs.
instances = Array(Array(instance.enumerated())[prefixItems.count...])
- What does
...
- What does
[prefixItems.count...]
when creating anArray
? - 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:
The
x...
is a one-sided range fromx
to "as far as possible", i.e., to the end of the array in case of subscripting, as done here.Array(instance.enumerated())
initializes an array from the enumerated sequenceinstance
, i.e.,[(Int, Any)]
. The subscript[prefixItems.count...]
takes the elements from that array starting from the indexprefixItems.count
and continuing to the end. The outerArray
initializes an array of that sequence.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.