2016-08-18 66 views
-1

我已儲存數組作爲字符串中的價格屬性,我想概括所有的價格點心項目

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

但它不工作

回答

1

使用等作爲below.Based您迅捷版選擇它。

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") 
       } 



      } 
+0

toInt()不工作 – lordxxx

+0

更新的答案進行檢查。 – Senthilkumar

+0

它不起作用 – lordxxx

0

這將增加你所有的價格屬性一起

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