Swift:带有Map的NSCountedSet

时间:2016-03-03 21:29:25

标签: swift swift2 ios9

我更愿意使用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}}吗?

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
}