代码之家  ›  专栏  ›  技术社区  ›  Hunter

swift:计算字典中的重复值

  •  3
  • Hunter  · 技术社区  · 8 年前

    我有一本字典 [uid: true, uid: false, uid: false, uid: false] .我如何在Swift中计算 true false 值,以便我可以看到有1个 真的

    5 回复  |  直到 8 年前
        1
  •  5
  •   deadbeef    8 年前

    最直接的方法是使用为此目的而设计的构造:计数集。没有本机Swift计数集,但您可以使用 NSCountedSet .

    let dict = [
        "key1": true,
        "key2": true,
        "key3": false
    ]
    
    let countedSet = NSCountedSet()
    for (_, value) in dict {
        countedSet.add(value)
    }
    print("Count for true: \(countedSet.count(for: true))")
    
        2
  •  5
  •   deanWombourne    8 年前

    使用 filter 方法删除不需要的值,然后调用 count

    // Get the count of everything which is true
    let trueCount = dict.filter { $0.value }.count
    
    // Get the count of everything which is false
    let falseCount = dict.filter { !$0.value }.count
    
    // A more efficient way to get the count of everything which is false
    let falseCount = dict.count - trueCount
    
        3
  •  0
  •   Lawrence Tan    8 年前

    您可以使用高阶函数,如 reduce :

    let trueFalstDict: [String: Bool] = ["id1": false, "id2": true, "id3": false, "id4": false]
    
    var trueFalseCount: (trues: Int, falses: Int)
    
    trueFalseCount.trues = trueFalstDict.reduce(0) { $0 + ($1.value ? 1 : 0) }
    trueFalseCount.falses = trueFalstDict.reduce(0) { $0 + ($1.value ? 0 : 1) }
    
    print(trueFalseCount) // (trues: 1, falses: 3)
    

    使用@DeanWomberne的建议:

    let trueFalstDict: [String: Bool] = ["id1": false, "id2": true, "id3": false, "id4": false]
    
    var trueFalseCount: (trues: Int, falses: Int)
    
    trueFalseCount = trueFalstDict.reduce((trues: 0, falses: 0)) {
        return (
            true: $0.trues + ($1.value ? 1 : 0),
            false: $0.falses + ($1.value ? 0 : 1)
        )
    }
    
    print(trueFalseCount) // (trues: 1, falses: 3)
    
        4
  •  0
  •   dfrib    8 年前

    let dict = [
        1: true,
        2: false,
        3: false,
        4: false
    ]
    

    使用 NSCountedSet :

    let numTrue = NSCountedSet(dict.values).count(for: true)
    let numFalse = dict.count - numTrue
    

    使用 reduce

    let numTrue = dict.values.reduce(0) { $0 + ($1 ? 1 : 0) }
    let numFalse = dict.count - numTrue
    

    这两种方法都利用了以下事实: Bool 仅允许两个不同的值,允许简单计算,例如 false true 计数(反之亦然)。

        5
  •  0
  •   Grzegorz R. Kulesza    7 年前

    例子:

    var currencyDB:[(name: String, value: Double, isShows: Bool, isMain: Bool)] = 
    [("USD",1.1588, true, true), 
    ("JPY",129.30, true, false), 
    ("BGN",1.9558, true, false), 
    ("CZK",25.657, true, false), 
    ("DKK",7.4526, false, false), 
    ("GBP",0.8905, false, false)]
    
    print(currencyDB.map{ $0.2 }.filter { $0 }.count))  // print: 4 -> trues
    print(currencyDB.map{ $0.2 }.filter { !$0 }.count)) // print: 2 -> falses