Swift: NSCountedSet with Map

ⅰ亾dé卋堺 提交于 2019-12-13 05:33:06

问题


I would prefer to use Person Struct, but I since it does not confirm to AnyObject, I can't use it with 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)  //

I would like to assign the "score" property in each object to the count of each object from NSCountedSet

I am trying to do this with Map. Code below does not compile.

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
}

I get the following error:

error: cannot convert value of type 'Person -> Person' to expected argument type '(Element) -> _'
let peopleWithUpdatedScore = countedPeople.map{( var person: Person) -> Person  in

Question1: How can resolve the error and achieve what I am trying to do?

Question2: Can I use a Struct instead of the a Person's class?


回答1:


Since NSCountedSet is not generic you'll need to cast the elements to Person.

let peopleWithUpdatedScore = countedPeople.map { (elm) -> Person in
    guard var person = elm as? Person else { fatalError() }
    person.score = countedPeople.countForObject(elm)
    return person
}


来源:https://stackoverflow.com/questions/35783399/swift-nscountedset-with-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!