如何在Swift中的布尔数组中找到许多True语句 [英] How can I find a number of True statements in an Array of Bools in Swift

查看:129
本文介绍了如何在Swift中的布尔数组中找到许多True语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名新开发人员,似乎无法弄清楚如何在布尔数组中查找True语句的数量.我知道如何按索引而不是按值查找.任何帮助将不胜感激.

I am a new developer and cannot seem to figure out how to find the number of True statements in an Array of Booleans. I know how to find by index but not by value. Any assistance would be appreciated.

let arrayElement = [Bool](repeating: false, count: 10)
var before: [[Bool]] = [[Bool]](repeating: arrayElement, count:10)
for i in 0 ..< 10 {
    for j in 0 ..< 10 {
        if arc4random_uniform(3) == 1 {
            before[i][j] = true  
        }        
    }
}

推荐答案

计算一维数组中true条目数的方法

一种方法是过滤Bool个元素的数组(对于true),然后简单地计算过滤后的数组中剩余元素的数量

Methods for counting number of true entries in a 1D array

One method would be to filter your array of Bool elements (for true) and simply count the number of remaining elements in the filtered array

let arr = [false, true, true, false, true]
let numberOfTrue = arr.filter{$0}.count
print(numberOfTrue) // 3

另一种方法是reduce(展开)数组并为等于true

Another approach is to reduce (unfold) the array and increment a counter for each element that equals true

let arr = [false, true, true, false, true]
let numberOfTrue = arr.reduce(0) { $0 + ($1 ? 1 : 0) }
print(numberOfTrue) // 3

或者,是传统的for循环(具有条件的循环签名)方法,可以与reduce方法媲美:

Or, a traditional for loop (with conditional in loop signature) approach, comparable top the reduce method:

let arr = [false, true, true, false, true]
var trueCounter = 0
for bElem in arr where bElem { trueCounter += 1 }
print(trueCounter) // 3

应用于您的示例:使用joined()实现一维数组

只需将.joined()应用于[[Bool]]数组以顺序构造[Bool]数组,即可轻松地将上述方法应用于数组数组(Bool个元素:类型[[Bool]]).

Applied to your example: use joined() to achieve a 1D array

The methods above can easily be applied to an array of arrays (of Bool elements: type [[Bool]]) by simply applying .joined() on the [[Bool]] array to sequentially construct a [Bool] array.

/* 'before' is of type [[Bool]], constructed as described
   in the question */
let numberOfTrueAlt1 = before.joined().filter{$0}.count

let numberOfTrueAlt2 = before.joined().reduce(0) { $0 + ($1 ? 1 : 0) }

var numberOfTrueAlt3 = 0
for bElem in before.joined() where bElem { numberOfTrueAlt3 += 1 }

这篇关于如何在Swift中的布尔数组中找到许多True语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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