核心数据中的项目总和

时间:2016-08-18 12:13:38

标签: ios swift core-data

我将数组中的price属性保存为String,我希望将所有价格相加

     if let fdf = cart.price{
        fdf.toInt()
    }

但它不起作用

2 个答案:

答案 0 :(得分:1)

使用如下所示。根据您的快速版本选择它。

var totalCount = 0;

                for i in 1...10 { 

//                Swift 1.x
                    let myString: String = "256"
                    let myInt: Int? = myString.toInt()
                    totalCount = totalCount + myInt! 

//                Swift 2.x
                    let myString: String = "256"
                    let myInt: Int? = Int(myString)
                    totalCount = totalCount + myInt!

                }

试试这种方式

for i in 1...10 {

                // Swift 1.x
                let myString: String = "256"


                if let number = myString.toInt() {
                    let myNumber = NSNumber(integer:number)
                    totalCount = totalCount + myNumber.integerValue
                    print(totalCount)
                } else {
                    print("'\(myString)' did not convert to an Int")
                }


                // Swift 2.x
                let myString: String = "256"
                let myInt: Int? = Int(myString)
                if let number = Int(myString) {
                    let myNumber = NSNumber(integer:number)
                    totalCount = totalCount + myNumber.integerValue
                    print(totalCount)
                } else {
                    print("'\(myString)' did not convert to an Int")
                }



            }

答案 1 :(得分:0)

这会将所有价格属性加在一起

var total = yourArray.reduce(0) { (a, b) in a + Int(b.price) }