Suppose I have an array, for example:

var myArray = ["Steve", "Bill", "Linus", "Bret"]

And later I want to push/append an element to the end of said array, to get:

["Steve", "Bill", "Linus", "Bret", "Tim"]

What method should I use?

And what about the case where I want to add an element to the front of the array? Is there a constant time unshift?

推荐答案

As of Swift 3 / 4 / 5, this is done as follows.

To add a new element to the end of an Array.

anArray.append("This String")

To append a different Array to the end of your Array.

anArray += ["Moar", "Strings"]
anArray.append(contentsOf: ["Moar", "Strings"])

To insert a new element into your Array.

anArray.insert("This String", at: 0)

To insert the contents of a different Array into your Array.

anArray.insert(contentsOf: ["Moar", "Strings"], at: 0)

More information can be found in the "Collection Types" chapter of "The Swift Programming Language", starting on page 110.

Ios相关问答推荐

自定义alert 未执行任何操作

preferredCompactColumn作为NavigationSplitViewColumn.sidebar传递,但仍能在iOS上看到详细信息页面

如何在后台显示 Swift UI 中的通讯通知?

由于缺少 libarclite_iphonesimulator.a 文件,将 XCode 升级到 14.3 后无法在模拟器上运行 Flutter 应用程序

更新 flutter 和 xcode 后 Xcode 14.3 中缺少文件 (libarclite_iphoneos.a)

核心媒体基础知识,了解 CMSampleBuffer、CMBlockBuffer 和 CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer

使用 SwiftUI 显示多个 VNRecognizedObjectObservation 边界框时偏移量错误

PropertyWrapper 不存在的 Codable 属性的默认值

如何从 Locale Swift 获取货币符号

'DismissAction'类型的值没有成员'wrappedValue'在SwiftUI的Xcode中

具有多个目标的应用程序的动态内容

使用 @MainActor 更新 UI 的适当策略是什么?

在向我的 struct 添加属性后获取线程 10:EXC_BAD_ACCESS (code=EXC_I386_GPFLT)

按钮在 SwiftUI 中没有采用给定的高度和宽度

通过touch 传递到下面的 UIViews

如何使用 sendAsynchronousRequest:queue:completionHandler:

UIView 和 initWithFrame 以及一个 NIB 文件.如何加载 NIB 文件?

Storyboard Segue 从视图控制器到自身

iOS UITextView 或 UILabel 带有可点击的动作链接

什么是强属性属性