Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert DispatchTimeInterval to NSTimeInterval (or Double)?

I need to subtract a DispatchTimeInterval from an NSTimeInterval (or Double).

Is there a standard way to convert a DispatchTimeInterval to an NSTimeInterval?

like image 386
meaning-matters Avatar asked Dec 08 '17 12:12

meaning-matters


1 Answers

DispatchTimeInterval is a enum:

public enum DispatchTimeInterval : Equatable {
    case seconds(Int)
    case milliseconds(Int)
    case microseconds(Int)
    case nanoseconds(Int)
    case never
}

You can initialize DispatchTimeInterval using:

    let tenSeconds: DispatchTimeInterval = .seconds(10)
    let tenNanoseconds: DispatchTimeInterval = .nanoseconds(10)

To get values from enum you need to match value with a case values in enum

    if case .seconds(let value) = tenSeconds {
        print("DispatchTimeInterval is seconds \(value)")
    } else if case .nanoseconds(let value) = tenNanoseconds {
        print("DispatchTimeInterval is seconds \(value)")
    }

Converting function might be look following:

func toDouble(_ interval: DispatchTimeInterval) -> Double? {
        var result: Double? = 0

        switch interval {
        case .seconds(let value):
            result = Double(value)
        case .milliseconds(let value):
            result = Double(value)*0.001
        case .microseconds(let value):
            result = Double(value)*0.000001
        case .nanoseconds(let value):
            result = Double(value)*0.000000001

        case .never:
            result = nil
        }

        return result
    }

More about Enumeration see in Apple Documentation

UPDATE:

Create extension to DispatchTimeInterval

extension DispatchTimeInterval {
    func toDouble() -> Double? {
        var result: Double? = 0

        switch self {
        case .seconds(let value):
            result = Double(value)
        case .milliseconds(let value):
            result = Double(value)*0.001
        case .microseconds(let value):
            result = Double(value)*0.000001
        case .nanoseconds(let value):
            result = Double(value)*0.000000001

        case .never:
            result = nil
        }

        return result
    }
}
like image 103
Ihar Katkavets Avatar answered Oct 06 '22 07:10

Ihar Katkavets