将 NSArray 转换为 NSMutableArray Swift [英] Convert NSArray to NSMutableArray Swift

查看:80
本文介绍了将 NSArray 转换为 NSMutableArray Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 self.assets NSArray 转换为 NSMutableArray 并将其添加到 picker.selectedAssets 是一个 NSMutableArray.这段代码在 swift 中会是什么样子?

Objective-C 代码

picker.selectedAssets = [NSMutableArray arrayWithArray:self.assets];

解决方案

在 Swift 5 中,NSMutableArray 有一个初始化器 init(array:),它继承自 NSArray.init(array:) 有以下声明:

convenience init(array anArray: NSArray)

<块引用>

通过将包含在给定数组中的对象放入新分配的数组来初始化新分配的数组.

<小时>

以下 Playground 示例代码展示了如何从 NSArray 的实例创建 NSMutableArray 的实例:

导入基础让 nsArray = [12, 14, 16] 作为 NSArray让 nsMutableArray = NSMutableArray(array: nsArray)nsMutableArray.add(20)打印(nsMutableArray)/*印刷:(12、14、16、20)*/

I'm trying to convert a the self.assets NSArray to NSMutableArray and add it to picker.selectedAssets which is a NSMutableArray. How will this code look like in swift?

Objective-C Code

picker.selectedAssets = [NSMutableArray arrayWithArray:self.assets];

解决方案

With Swift 5, NSMutableArray has an initializer init(array:) that it inherits from NSArray. init(array:) has the following declaration:

convenience init(array anArray: NSArray)

Initializes a newly allocated array by placing in it the objects contained in a given array.


The following Playground sample code shows hot to create an instance of NSMutableArray from an instance of NSArray:

import Foundation

let nsArray = [12, 14, 16] as NSArray
let nsMutableArray = NSMutableArray(array: nsArray)
nsMutableArray.add(20)
print(nsMutableArray)

/*
prints:
(
    12,
    14,
    16,
    20
)
*/

这篇关于将 NSArray 转换为 NSMutableArray Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆