使用Swift计算嵌套数组中的唯一ID

时间:2018-10-27 11:30:03

标签: arrays swift

我有以下嵌套数组,并且我试图计算有多少个具有唯一ids的项。在下面的数组中,计数应为2。

数组的类型为List<SolData>,它来自Realm

class SolData: Object {
    @objc dynamic var uid = "";
    @objc dynamic var id = "";
}

extension SolData: ListDiffable {
    func diffIdentifier() -> NSObjectProtocol {
        return uid as NSObjectProtocol
    }

    func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
        if let object = object as? SolData {
            return uid == object.uid
        }
        return false
    }
}

打印数组。

 (
    [0] SolData {
        uid = sdasd;
        id = jmX3;
    },
    [1] SolData {
        uid = gfd;
        id = jmX3;
    },
    [2] SolData {
        uid = hgfd;
        id = jmX3;
    },
    [3] SolData {
        uid = terw;
        id = jmX3;
    },
    [4] SolData {
        uid = fgg;
        id = GFdda;
    }
)

我尝试通过以下方式使用map

var count = 0;
var prevId = "";

let uniqueSols = diff.sol.map{ (s) -> Int in
  if s.id != prevId {
    count = count + 1;
    prevId = s.id;
  }
  return count;
}

print(uniqueSols);

但是出现以下错误。

  

SWIFT RUNTIME BUG:无法取消整理字段'_transform'的类型。整齐的类型名称是'q_7ElementSTQzc'   2018-10-27 14:26:08.793528 + 0300 App [23634:611928] SWIFT运行时错误:无法取消整理字段'_transform'的类型。整齐的类型名称是'q_7ElementSTQzc',_transform:())

1 个答案:

答案 0 :(得分:2)

要重现您的代码,我将模拟SolData类并添加一个初始化程序以简化实例化:

class SolData {
    var uid: String = ""
    var id: String = ""

    init(uid: String, id: String) {
        self.uid = uid
        self.id  = id
    }
}

让我们创建一些实例:

let zero  = SolData(uid: "sdasd", id: "jmX3")
let one   = SolData(uid: "gfd",   id: "jmX3")
let two   = SolData(uid: "hgfd",  id: "jmX3")
let three = SolData(uid: "terw",  id: "jmX3")
let four  = SolData(uid: "fgg",   id: "GFdda")

并将它们分组为一个数组:

let array = [zero, one, two, three, four]

要仅获取具有唯一ID的实例,请使用reduce(into:)

let uniqueIds = array.reduce(into: Set<String>(), { $0.insert($1.id)})

uniqueIds的count属性是array中唯一ID的数量:

let uniqueIdsCount = uniqueIds.count  //2

如果要使用具有唯一ID的实例数组,请使用以下命令:

let instancesWithUniqueIds = array.reduce(into: [SolData]()) { accumulator, element in
    if accumulator.allSatisfy({ $0.id != element.id}) {
        accumulator.append(element)
    }
}

accumulator.allSatisfy({ $0.id != element.id})可以替换为accumulator.contains(element),并使SolData符合Hashable