【问题标题】:How to check how many true and how many false items is in Array (SWIFT3) [duplicate]如何检查数组中有多少真实和多少虚假项目(SWIFT3)[重复]
【发布时间】:2017-07-13 16:58:48
【问题描述】:

我需要一些帮助。我想检查数组中有多少布尔值 (true,false)。如何仅使用 if 语句进行检查。

var voteArray: Bool = [true,false,true,false,true,true,false,false,true]

然后,将[true] 添加到其他数组,将[false] 添加到其他数组

【问题讨论】:

    标签: arrays swift if-statement boolean


    【解决方案1】:

    你可以filter你的数组。

    var voteArray = [true,false,true,false,true,true,false,false,true]
    let trueArray = voteArray.filter { $0 }
    let falseArray = voteArray.filter { !$0 }
    //If you want count also then simply access count property of both trueArray and falseArray
    

    编辑:正如你在评论中提到你想用for loop 来处理这个问题,我不知道你为什么要这样,但你已经问过了,所以你可以这样.

    var voteArray = [true,false,true,false,true,true,false,false,true]
    var trueArray = [Bool]()
    var falseArray = [Bool]()
    for item in voteArray {
        if item {
            trueArray.append(item)
        }
        else {
            falseArray.append(item)
        }
    }
    
    //Or you can go with individual for loop for both true and false
    
    //For true
    for item in voteArray where item {
        trueArray.append(item)
    } 
    
    //For false
    for item in voteArray where !item {
        falseArray.append(item)
    } 
    

    【讨论】:

    • 我知道我在堆栈上找到了这个方法,但我尝试使用 if 语句来实现,你知道怎么做吗?
    • @Marcin 你能解释一下你想要什么吗,如果更详细地编辑你的问题,你的意思是什么。
    • 我想创建一个 for...in 循环,循环遍历其中一个投票集合并检查每个投票的值。如果投票为真,则循环应为 yes 变量添加一票。如果它是假的,它应该给 no 变量加一票。
    • @Marcin 你的意思是你想使用 for 循环一个一个地追加对象,那有什么必要?
    • 是的,你能帮忙吗?
    猜你喜欢
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 2018-02-25
    相关资源
    最近更新 更多