计算数组数组中的项目? [英] Count Items in an Array of Arrays?
本文介绍了计算数组数组中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个声明为
let compoundArray = [Array<String>]
是否有一个属性可以给我compoundArray中包含的所有数组中的字符串数?
is there a property that would give me the number of strings in all the arrays contained in compoundArray?
我可以通过将每个数组中的所有项相加来做到这一点:
I can do it by adding up all the items in each array within:
var totalCount = 0
for array in compoundArray {
totalCount += array.count }
//totalCount = total items in all arrays within compoundArray
但是这似乎很笨拙,而且看来swift将具有Array的属性/方法来执行此操作,不是吗?
But that seems clunky and it seems that swift would have a property/method of Array to do this, no?
谢谢!
推荐答案
您可以为此使用joined
或flatMap
.
使用joined
Using joined
let count = compoundArray.joined().count
使用flatMap
Using flatMap
let count = compoundArray.flatMap({$0}).count
这篇关于计算数组数组中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文