问题
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