如何在ios swift 4中多个两个字符串数组并获得总值 [英] How to Multiple Two String Arrays and get total value in ios swift 4

查看:28
本文介绍了如何在ios swift 4中多个两个字符串数组并获得总值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个如下所示的数组,我想计算 2 个数组值并根据数量获得总值.[1",1"][129.95 英镑"、129.95 英镑"]

I have Two arrays like below i a want calculate 2 array values and get total value according to qty. ["1", "1"] ["£129.95", "£129.95"]

推荐答案

我不确定您是否要在两个数组中添加/多个数字.并且不确定您想从两个数组中计算出什么.所以我在下面添加了示例代码来添加和多个两个字符串数组.

I'm not sure if you want to add/multiple numbers in both array. And not sure what do you want to calculate from two arrays. So I've added example code below to add and multiple two string arrays.

func calculateTwoArrays(){

        let array1 = ["1", "1"]
        let array2 = ["£129.95", "£129.95"]

        //Add all values together
        var total:Double = 0.0

        for value in array1 {

            if let number = Double(value.replacingOccurrences(of: "£", with: "")){

                total += number
            }
        }

        print("Total:\(total)")

        //Multiply array values, assuming array1 as quantity and array 2 as price.
        var priceArray = [Double]()

        for quantity in array1 {

            for price in array2 {

                if let quantityValue = Double(quantity), let priceValue = Double(price.replacingOccurrences(of: "£", with: "")){

                    priceArray.append(quantityValue*priceValue)
                }
            }
        }

        total = priceArray.reduce(0, +)

        print("Total:\(total)")
}

这篇关于如何在ios swift 4中多个两个字符串数组并获得总值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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