Swift闭包迭代一个类对象

时间:2017-01-27 14:49:17

标签: swift

很想知道是否有人有一个快速闭包解决方案来在包含多个类对象的数组上转换以下for / in循环迭代?该类由string类型的两个属性组成。类函数实例化多个对象并将它们放入数组中。在下面的示例中,数组nhSearchObject有10个索引,包含该类的10个对象。

class President{
   var firstName:String 
   var lastName:String
    init(...)
    }       
  // class function creates objects and places them into an array   nhSearchObject

for i in nhSearchObject[0...6] {
    i.firstName = "George"
    i.lastName = "Washington"
}

必须保留下标范围功能,因为我只想更改索引0 ... 6。另外,我不想创建一个新的数组。只想对迭代现有数组的10个索引的数组切片0..6来修改对象属性。

2 个答案:

答案 0 :(得分:2)

首先,您的课程为President(无Presidents

class President {
    var firstName:String
    var lastName:String
    init(firstName: String, lastName:String) {
        self.firstName = firstName
        self.lastName = lastName
    }
}

现在给出以下数组

let presidents: [President] = ...

你可以遵循2种方法

如果您确定阵列至少有7个元素,那么

presidents[0...6].forEach { president in
    president.firstName = "George"
    president.lastName = "Washington"
}

否则

presidents
    .enumerated()
    .filter { $0.offset <= 6 }
    .forEach { elm in
        elm.element.firstName = "George"
        elm.element.lastName = "Washington"
    }

答案 1 :(得分:-1)

nhSearchObject.forEach {$ 0.firstName =&#34; George&#34 ;; $ 0.lastName =&#34;华盛顿&#34; }