Swift:带有地图的NSCountedSet [英] Swift: NSCountedSet with Map

查看:94
本文介绍了Swift:带有地图的NSCountedSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我更愿意使用Person Struct,但是由于它不能确认AnyObject,所以我不能在NSCountedSet

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)  //

我想将每个对象中的"score"属性分配给NSCountedSet

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

我正在尝试使用Map进行此操作.以下代码无法编译.

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
}

我收到以下错误:

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

问题1:如何解决该错误并实现我想做的事情?

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

问题2:我可以使用Struct代替Personclass吗?

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

推荐答案

由于NSCountedSet不是通用的,因此需要将元素强制转换为Person.

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
}

这篇关于Swift:带有地图的NSCountedSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆