我正在尝试制作一个对象的多个副本然后追加到一个数组中。我正在将我的对象转换为NSObject以使用方法“copy()”,但是,我希望立即拥有该对象的“n”个副本并将它们全部附加到现有数组中。例如,见下文:
var okay = "okay"
var NSOkay = okay as NSObject
var copyOkay: AnyObject = NSOkay.copy()
var array = [String]()
array.append(copyOkay as! String)
但是,这会附加我的项目的唯一副本。可以说,我希望追加10个项目的副本,那我该怎么做?
非常感谢,
答案 0 :(得分:0)
默认情况下复制值类型(看看here)。除了显而易见的for循环方式之外,还有另一种方法:
import Foundation
//the string
let okay = "okay"
//There is no need to convert a String to NSObject
let NSOkay = okay as NSObject
//number of copies
let n = 3
//pre-existing array
var array : [NSObject] = ["Well", "then"]
array += Array(count: n, repeatedValue: NSOkay) //["Well", "then", "okay", "okay", "okay"]