我更愿意使用Person
Struct
,但由于它未向AnyObject
确认,因此无法将其用于NSCountedSet
class Person: AnyObject {
var name: String = ""
var age: Int = 0
var score: Int = 0
}
let personA = Person()
personA.name = "john"
let personB = Person()
personB.name = "larry"
let personC = Person()
personC.name = "jack"
let personD = Person()
personD.name = "bob"
var people:[AnyObject] = [personD, personC, personA, personB, personC, personA, personC, personD, personD]
let countedPeople = NSCountedSet(array: people) //
我想将每个对象中的“得分”属性分配给NSCountedSet
我正在尝试使用Map
执行此操作。下面的代码无法编译。
let peopleWithUpdatedScore = countedPeople.map{( var person: Person) -> Person in
// I would like to assign the count of each Object as the persons score.
person.score = countForObject(person)
return person
}
我收到以下错误:
error: cannot convert value of type 'Person -> Person' to expected argument type '(Element) -> _'
let peopleWithUpdatedScore = countedPeople.map{( var person: Person) -> Person in
问题1:如何解决错误并实现我想要做的事情?
问题2:我可以使用Struct
代替Person
的{{1}}吗?
答案 0 :(得分:1)
由于NSCountedSet
不是通用的,因此您需要将元素转换为Person
。
let peopleWithUpdatedScore = countedPeople.map { (elm) -> Person in
guard var person = elm as? Person else { fatalError() }
person.score = countedPeople.countForObject(elm)
return person
}