Another convenient way to convert an ArraySlice to Array is this:
var tags = ["this", "is", "cool"]
var someTags: [String] = tags[1..<3] + []
It's not perfect because another developer (or yourself) who looks at it later may not understand its purpose. The good news is that if that developer (maybe you) removes the + [] they will immediately be met with a compiler error, which will hopefully clarify its purpose.
Another way to do that in one place is combine variable declaration let someTags: [String] and map(_:), that will transform ArraySlice<String> to [String]:
let tags = ["this", "is", "cool"]
let someTags: [String] = tags[1..<3].map { $0 } // ["is", "cool"]
Subscripting an array with a range doesn't return an array, but a slice. You can create an array out of that slice though.
You can also do this to get a new array of the slice:
Another convenient way to convert an
ArraySlice
toArray
is this:var tags = ["this", "is", "cool"] var someTags: [String] = tags[1..<3] + []
It's not perfect because another developer (or yourself) who looks at it later may not understand its purpose. The good news is that if that developer (maybe you) removes the
+ []
they will immediately be met with a compiler error, which will hopefully clarify its purpose.Another way to do that in one place is combine variable declaration
let someTags: [String]
andmap(_:)
, that will transformArraySlice<String>
to[String]
: