如何通过多个元素过滤数组并在Swift中找到总和?(How to filter the array by multiple element and find the sum in Swift?)

我试图通过一些元素来过滤我的数组。 我想记录类型包含“收入”和$0.createdAt!等于一个日期,但$0.createdAt! 是一个日期类型,所以我不能使用.contain("") ,我可以使用什么?

recordFilter = record.filter { $0.recordtype!.contains("Income") /*|| $0.createdAt! = recordItem.createdAt!*/}

recordFilter输出:(此结果不是由createdAt过滤)

[<Record: 0x600000099fa0> (entity: Record; id: 0xd0000000003c0000 <x-coredata://913F25A5-B2C9-4646-9091-5EFE7F906908/Record/p15> ; data: {
    accountbook = "first book";
    amount = "\U00a59.99";
    assest = nil;
    category = "\U6295\U8d44";
    createdAt = "2017-11-16 16:00:00 +0000";
    date = nil;
    id = 15;
    recordtype = "\U6536\U5165";
    remark = "";
    toAccBook = nil;
}), <Record: 0x600000099ff0> (entity: Record; id: 0xd000000000400000 <x-coredata://913F25A5-B2C9-4646-9091-5EFE7F906908/Record/p16> ; data: {
    accountbook = "first book";
    amount = "\U00a56.58";
    assest = nil;
    category = "\U5de5\U8d44";
    createdAt = "2017-11-16 16:00:00 +0000";
    date = nil;
    id = 16;
    recordtype = "\U6536\U5165";
    remark = "";
    toAccBook = nil;
})]

之后,我尝试获取数组中的所有数量字符串并对其进行求和。 但是当我使用这段代码的时候,我发现它全部是单独的字符串,我怎样才能将它分组到数组中并且对它进行求和或者有其他方法来做到这一点?

let sum = recordFilter.map({Int($0.amount!.dropFirst())})
//[nil, nil]

for i in 0..<recordFilter.count{
    if recordFilter[i].amount != nil{

        let amountList = recordFilter[i].amount!.dropFirst()
        print(amountList) // I found that it's separate string.
        //9.99
        //11.22
        // ...

        //let intArray = amountList.map { Int($0)!}
        //let sum = amountList.reduce(0, +)
        //print(sum)

    }
}

I'm trying to filter my array by some element. I want recordtype is contain "Income" and createdAt equal to a date but $0.createdAt! is an date type so I can't use .contain(""), what can I use?

recordFilter = record.filter { $0.recordtype!.contains("Income") /*|| $0.createdAt! = recordItem.createdAt!*/}

recordFilter output: (this result is not filter by createdAt yet)

[<Record: 0x600000099fa0> (entity: Record; id: 0xd0000000003c0000 <x-coredata://913F25A5-B2C9-4646-9091-5EFE7F906908/Record/p15> ; data: {
    accountbook = "first book";
    amount = "\U00a59.99";
    assest = nil;
    category = "\U6295\U8d44";
    createdAt = "2017-11-16 16:00:00 +0000";
    date = nil;
    id = 15;
    recordtype = "\U6536\U5165";
    remark = "";
    toAccBook = nil;
}), <Record: 0x600000099ff0> (entity: Record; id: 0xd000000000400000 <x-coredata://913F25A5-B2C9-4646-9091-5EFE7F906908/Record/p16> ; data: {
    accountbook = "first book";
    amount = "\U00a56.58";
    assest = nil;
    category = "\U5de5\U8d44";
    createdAt = "2017-11-16 16:00:00 +0000";
    date = nil;
    id = 16;
    recordtype = "\U6536\U5165";
    remark = "";
    toAccBook = nil;
})]

After that, I trying to get all the amount string in array and sum it. But I found that it's all separate string when I use this code, how can I group it in array and sum it or have any other way to do it?

let sum = recordFilter.map({Int($0.amount!.dropFirst())})
//[nil, nil]

for i in 0..<recordFilter.count{
    if recordFilter[i].amount != nil{

        let amountList = recordFilter[i].amount!.dropFirst()
        print(amountList) // I found that it's separate string.
        //9.99
        //11.22
        // ...

        //let intArray = amountList.map { Int($0)!}
        //let sum = amountList.reduce(0, +)
        //print(sum)

    }
}

原文:https://stackoverflow.com/questions/47343382
2023-03-11 17:03

满意答案

原因是正则表达式中有<符号,并且在浏览器中它们被解释为标记。 要避免此类行为,您可以通过htmlspecialchars转义此类字符:

echo htmlspecialchars('/' . $this->rules['usuario']['regexp'] . '/');

The reason is that there are < symbols in the regexp, and in the browser they are interpreted as tags. To avoid such behavior, you can escape such characters via htmlspecialchars:

echo htmlspecialchars('/' . $this->rules['usuario']['regexp'] . '/');

相关问答

更多

使用PHP在数组中存储数组(Storing array within an array using PHP)

步骤1.用$topicarray[$value][]替换$topicarray[$value] $topicarray[$value][] 第2步。 ??? 第3步。利润 Step 1. Replace $topicarray[$value] with $topicarray[$value][] Step 2. ??? Step 3. Profit

PHP RegEx拆分为2D数组?(PHP RegEx split to 2D array?)

您可以在正则表达式中使用命名组: $str = "C1 X2 B10"; $re = '~(?P<type>[A-Z])(?P<number>\d+)~'; preg_match_all($re, $str, $m, PREG_SET_ORDER); print_r($m); 给你的 Array ( [0] => Array ( [0] => C1 [type] => C [1] => C ...

使用REGEX查找PHP(Find PHP with REGEX)

使用token_get_all您将获得给定PHP代码的PHP语言标记列表。 然后,您只需要迭代列表,查找打开的标记令牌以及相应的关闭标记。 $blocks = array(); $opened = false; foreach (token_get_all($code) as $token) { if (!$opened) { if (is_array($token) && ($token[0] === T_OPEN_TAG || $token[0] === T_OPEN_...

在数组上执行正则表达式并存储在另一个数组中(doing a regex on an array and storing in another array)

你可以试试这个: <?php $files=["ffg_LTE_2016-06-13","ffg_LTE_2016-06-14"]; $re = '/(\d{8})|([0-9]{4}-[0-9]{2}-[0-9]{2})|([0-9]{2}-[0-9]{2}-[0-9]{4})/'; $results = []; foreach ($files as $value) { preg_match($re, $value, $matches); ...

在PHP Regex中需要帮助(Need Help in PHP Regex)

\w仅代表单词字符,您还需要允许空格。 假设你真的想在-start-和-end-之间允许任何东西 - 你可以使用. 匹配任何角色。 除非用字符模式(在方括号[和]之间)括起来,否则不需要对连字符进行转义,因此可以用\-替换\- - 。 就像使用单个\w表示匹配任何单个单词字符一样. 表示匹配任何单个字符,因此您需要添加更多信息。以下任何一个用+表示匹配至少一个字符,或用*表示零个或多个字符。 假设你想要至少一个角色,你的表达应该是这样的: $pattern = "/-start-(.+)-end-...

Php:正则表达式 - 如何提取匹配的多个部分并将其存储在数组中?(Php:Regex-How to extract multiple portions of match and store it in an array?)

拆分完整的字符串依据: /<ul.*?>/m 然后遍历拆分并应用以下正则表达式来捕获斜体值“ /<i>(.*?)<\/i>/m 在这里运行它 源: <?php $re = '/<ul.*?>/m'; $re1 = '/<i>(.*?)<\/i>/m'; $str = '<ul class="food"> <li> <i>Bread and Butter</i> </li> <li> <i>Cheese</i> </li> <li> <i>Milk</i> </li> </ul> <ul cl...

PHP / MySQL - 将数组存储在数据库中(PHP/MySQL - Storing array in database)

真正的原因是正常化,你将通过这样做来打破第一个正常形态 。 但是,有很多情况下可以考虑违反正常形式。 你打交道的领域有多少?他们都是布尔人吗? 在数据库中存储序列化为字符串的数组将具有以下缺点(等等): 当您需要更新设置时,您必须首先从数据库中提取当前设置,反序列化数组,更改数组,更改数组并更新表中的数据。 在搜索时,您将无法只向数据库询问给定用户(或一组用户)是否禁用或启用了给定设置,因此您不会有任何搜索机会。 相反,您应该真的考虑使用另一个表创建另一个表,并将您需要的记录作为另一个表的一对多关...

Regex PHP中的'['和']'('[' and ']' in Regex PHP)

你也需要逃离开口支架。所以要更换 $t = preg_match('/[(.*?)\]/s', $s, $matches); 同 $t = preg_match('/\[(.*?)\]/s', $s, $matches); You need to escape the opening bracket also.So replace $t = preg_match('/[(.*?)\]/s', $s, $matches); with $t = preg_match('/\[(.*?)\]/s'...

在数组PHP中存储REGEX(Storing REGEX in array PHP)

原因是正则表达式中有<符号,并且在浏览器中它们被解释为标记。 要避免此类行为,您可以通过htmlspecialchars转义此类字符: echo htmlspecialchars('/' . $this->rules['usuario']['regexp'] . '/'); The reason is that there are < symbols in the regexp, and in the browser they are interpreted as tags. To avoid ...

PHP中的RegEx返回数组(RegEx in PHP to return array)

如果它始终采用该格式,请使用preg_match_all() ,如下所示: preg_match_all( '#\{image id="(\d+)"[^\}]+\}#', $input, $matches); 您的ID数组将位于$matches[1] 。 因此,对于您的示例输入,此输出 : array(1) { [0]=> string(5) "27411" } If it's always in that format, use preg_match_all(), like this...

相关文章

更多

千锋首发Swift视频教程

千锋Swift视频教程-7.Swift结构体.mp4 千锋Swift视频教程-13.代理反向传值.mp ...

Swift入门视频教程-尚学堂视频教程

最新Swift语言语法介绍,包括Swift流程控制语句、Swift各种构造函数、closure、泛型、 ...

lucene4.7 过滤Filter(六)

先介绍下查询与过滤的区别和联系,其实查询(各种Query)和过滤(各种Filter)之间非常相似,可以 ...

The content of element type "package" must match "...

在编写后台登陆模块时,将许多默认的设置放在一个名为default的package 里。然后再定义其他 ...

could not find system property or JNDI

Thanks everyone!! Finally got a solution for this p ...

java.lang.ClassNotFoundException: org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter的解决方案

struts2.0.x到struts 2.1.2使用的核心 过滤器是FilterDispatcher, ...

Solr4:利用Filter实现两组关键词组合查询

本文参考:Lucene4.1:利用Filter实现两组关键词组合查询 1. 需求 根据客户名称,查询 ...

Filter 简单应用实例求详解

web.xml &lt;filter&gt; &lt;filter-name&gt;AdminFi ...

线性渐变-linear-gradient和滤镜opacity/filter的透明效果兼容性解决方案及其RGB/RGBA与16进制转换方法

第一篇:滤镜opacity/filter的透明效果兼容性解决方案RGB/RGBA介绍 项目中需要实现透 ...

移动MM failed to find resource file{mmiap.xml}

原地址:http://blog.csdn.net/alking_sun/article/details ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本