In Swift, Array [String] slicing return type doesn

2019-01-04 11:53发布

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

5条回答
放我归山
2楼-- · 2019-01-04 12:04

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)
查看更多
Summer. ? 凉城
3楼-- · 2019-01-04 12:11
var tags = ["this", "is", "cool"]
var someTags: [String] = Array(tags[1..<3])
println("someTags: \(someTags)") // "someTags: [is, cool]"
查看更多
冷血范
4楼-- · 2019-01-04 12:17

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"]
查看更多
Emotional °昔
5楼-- · 2019-01-04 12:17

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.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-01-04 12:22

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"]
查看更多
登录 后发表回答