In Swift, Array [String] slicing return type doesn't seem to be [String]

IosSwiftSub Array

Ios Problem Overview


I'm slicing an array of strings and setting that to a [String] variable, but the type checker is complaining. Is it a possible compiler bug?

var tags = ["this", "is", "cool"]
tags[1..<3]
var someTags: [String] = tags[1..<3]

> screenshot

Ios Solutions


Solution 1 - Ios

Subscripting an array with a range doesn't return an array, but a slice. You can create an array out of that slice though.

var tags = ["this", "is", "cool"]
tags[1..<3]
var someTags: Slice<String> = tags[1..<3]
var someTagsArray: [String] = Array(someTags)

Solution 2 - Ios

var tags = ["this", "is", "cool"]
var someTags: [String] = Array(tags[1..<3])
println("someTags: \(someTags)") // "someTags: [is, cool]"

Solution 3 - Ios

You can also do this to get a new array of the slice:

var tags = ["this", "is", "cool"]
var someTags = [String]()
someTags += tags[1..<3]
println(someTags[0])  //prints ["is", "cool"]

Solution 4 - Ios

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"]

Solution 5 - Ios

Another convenient way to convert an ArraySlice to Array is this:

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.

Solution 6 - Ios

Just cast the slice as an Array when it's created. Keeping your Array as an array without having to use an intermediate variable. This works great when using Codable types.

var tags = ["this", "is", "cool"]
tags = Array(tags[1..<3])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLiron ShapiraView Question on Stackoverflow
Solution 1 - IosConnorView Answer on Stackoverflow
Solution 2 - IoszaphView Answer on Stackoverflow
Solution 3 - IosSteve RosenbergView Answer on Stackoverflow
Solution 4 - IospacificationView Answer on Stackoverflow
Solution 5 - IosjeremyabannisterView Answer on Stackoverflow
Solution 6 - IosStarPlayrXView Answer on Stackoverflow