var mentions = ["@alex", "@jason", "@jessica", "@john"]
我想将我的数组限制为 3 个项目,所以我想拼接它:
var slice = [String]()
if mentions.count > 3 {
slice = mentions[0...3] //alex, jason, jessica
} else {
slice = mentions
}
但是,我得到:
Ambiguous subscript with base type '[String]' and index type 'Range'
Apple Swift 版本 2.2 (swiftlang-703.0.18.8 clang-703.0.31) 目标:x86_64-apple-macosx10.9
最佳答案
问题是 mentions[0...3]
返回 ArraySlice<String>
,不是 Array<String>
.因此,您可以先使用 Array(_:)
将切片转换为数组的初始化程序:
let first3Elements : [String] // An Array of up to the first 3 elements.
if mentions.count >= 3 {
first3Elements = Array(mentions[0 ..< 3])
} else {
first3Elements = mentions
}
或者如果你想使用 ArraySlice
(它们对于中间计算很有用,因为它们在原始数组上呈现“ View ”,但不是为长期存储而设计的),您可以下标 mentions
在您的 else
中包含所有索引:
let slice : ArraySlice<String> // An ArraySlice of up to the first 3 elements
if mentions.count >= 3 {
slice = mentions[0 ..< 3]
} else {
slice = mentions[mentions.indices] // in Swift 4: slice = mentions[...]
}
虽然到目前为止最简单的解决方案就是使用 prefix(_:)
方法,它将返回 ArraySlice
前 n 个元素的一部分,或者如果 n 超过数组计数则整个数组的一部分:
let slice = mentions.prefix(3) // ArraySlice of up to the first 3 elements
关于ios - 如何在 Swift 中执行数组切片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38797663/