ios 在 Swift 中,数组 [String] 切片返回类型似乎不是 [String]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25714673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Swift, Array [String] slicing return type doesn't seem to be [String]
提问by Liron Shapira
回答by Connor
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)
回答by zaph
var tags = ["this", "is", "cool"]
var someTags: [String] = Array(tags[1..<3])
println("someTags: \(someTags)") // "someTags: [is, cool]"
回答by pacification
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 someTags: [String]
和map(_:)
,这将转换ArraySlice<String>
为[String]
:
let tags = ["this", "is", "cool"]
let someTags: [String] = tags[1..<3].map { var tags = ["this", "is", "cool"]
tags = Array(tags[1..<3])
} // ["is", "cool"]
回答by jeremyabannister
Another convenient way to convert an ArraySlice
to Array
is this:
另一种将 an 转换为ArraySlice
to 的便捷方法Array
是:
var tags = ["this", "is", "cool"]
var someTags: [String] = tags[1..<3] + []
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.
它并不完美,因为稍后查看它的其他开发人员(或您自己)可能不理解其目的。好消息是,如果该开发人员(也许是您)删除了+ []
它们,他们将立即遇到编译器错误,这有望阐明其目的。
回答by StarPlayrX
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.
只需在创建切片时将其转换为数组即可。将您的 Array 保持为一个数组,而不必使用中间变量。这在使用 Codable 类型时非常有效。
var tags = ["this", "is", "cool"]
var someTags = [String]()
someTags += tags[1..<3]
println(someTags[0]) //prints ["is", "cool"]
回答by Steve Rosenberg
You can also do this to get a new array of the slice:
您也可以这样做来获取切片的新数组:
##代码##