In Swift, an array of the returned array type [String] does not look like [String]

I slice an array of strings and set it to the [String] variable, but it checks the type of check. Is this a possible compiler error?

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

screenshot

+84
ios swift sub-array
Sep 07 '14 at 20:50
source share
5 answers

Signing an array with a range does not return an array, but a slice. However, you can create an array from this fragment.

 var tags = ["this", "is", "cool"] tags[1..<3] var someTags: Slice<String> = tags[1..<3] var someTagsArray: [String] = Array(someTags) 
+164
Sep 07 '14 at 20:58 on
source share
 var tags = ["this", "is", "cool"] var someTags: [String] = Array(tags[1..<3]) println("someTags: \(someTags)") // "someTags: [is, cool]" 
+14
07 Sep '14 at 22:07
source share

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

 var tags = ["this", "is", "cool"] var someTags = [String]() someTags += tags[1..<3] println(someTags[0]) //prints ["is", "cool"] 
0
Sep 07 '14 at 21:13
source share

Another way to do this in one place is to declare the variable let someTags: [String] and map(_:) , which convert ArraySlice<String> to [String] :

 let tags = ["this", "is", "cool"] let someTags: [String] = tags[1..<3].map { $0 } // ["is", "cool"] 
0
Apr 21 '18 at 11:29
source share

Another convenient way to convert ArraySlice to Array is to:

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

This is not ideal, because another developer (or himself) who looks at him later may not understand his goals. The good news is that if this developer (maybe you) removes + [] they will be immediately greeted with a compiler error, which I hope will clarify its purpose.

0
Oct. 16 '18 at 22:32
source share



All Articles