如何添加两次?

时间:2017-11-03 08:38:59

标签: ios swift

我知道这是一个非常基本的问题,我正在开发一个活动应用程序,其中我从webservice以格式(HH.MM)获得字符串数组时间为[00.30.00,00.30.00,00.30.00] .SS),我的任务是添加时间并显示为01.30.00。谁能指导我?感谢。

import UIKit

class ViewController: UIViewController {

var timeArray = ["00.30.00","00.30.00","00.30.00"]
var sepratedArray:[Time] = []

override func viewDidLoad() {
    super.viewDidLoad()

    for items in timeArray {
        let tempArray = items.components(separatedBy: ".")
        sepratedArray.append(Time(hours: Double(tempArray[0])!, minutes: Double(tempArray[1])!, Seconds: Double(tempArray[2])!))
    }
    print(sepratedArray)

   for item in 0...sepratedArray.count-1 {
        _ = Int(sepratedArray[item].Seconds)
        _ = Int(sepratedArray[item].minutes)
        _ = Int(sepratedArray[item].hours)+1
    }
    print("count ary is: \(sepratedArray)")
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}
struct Time
{
var hours: Double
var minutes: Double
var Seconds: Double
}

1 个答案:

答案 0 :(得分:2)

您可以使用此函数计算总和,同时考虑到秒和分钟的值不应高于59(请注意,此函数不能处理错误的格式):

func sum(_ timeArray: [String]) -> String {
    var sum = [0, 0, 0]
    for time in timeArray {
        let components = time.split(separator: ".")
        sum[0] += Int(components[0])!
        sum[1] += Int(components[1])!
        sum[2] += Int(components[2])!
    }

    for componentIndex in [2, 1] {
        while sum[componentIndex] > 59 {
            sum[componentIndex] -= 60
            sum[componentIndex - 1] += 1
        }
    }

    return String(format: "%02d.%02d.%02d", sum[0], sum[1], sum[2])
}
像这样:

let time = ["00.30.00", "00.30.00", "00.30.00"]
print(sum(time)) // prints 01.30.00