我试图制作一个对象的多个副本,然后追加到数组中。我将对象转换为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个副本,然后该怎么办?

非常感谢你,

最佳答案

默认情况下,将复制值类型(请查看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"]

09-25 15:31