ios - 如何在 Swift 中执行数组切片?

标签 ios swift

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/

相关文章:

ios - iOS 上类似 Google Now 的界面

ios - 在 xcode 8 中使用 Swift 3 出现未知错误 - "Editor placeholder in source file"

swift - 约束字典的协议(protocol)扩展

ios - 手势更新中的快速崩溃

ios - 在边框 Swift SpriteKit 上绘制具有多种颜色的空圆

android - react native /博览会 : Push notifications for standalone Apps

ios - 使用 SearchController 进行搜索时使用标签栏出现黑屏

ios - 使用 Alamofire 将结构上传到服务器

ios - 快速迭代数组以从 firebase 数据库中提取值

swift - 使用粒子效果或动画 sks 文件创建填充字母