I'm using swift 3, to make delayed events, this is the code
public func delay(bySeconds seconds: Double, dispatchLevel: DispatchLevel = .main, closure: @escaping () -> Void)
{
let dispatchTime = DispatchTime.now() + seconds
dispatchLevel.dispatchQueue.asyncAfter(deadline: dispatchTime, execute: closure)
}
public enum DispatchLevel
{
case main, userInteractive, userInitiated, utility, background
var dispatchQueue: DispatchQueue
{
switch self
{
case .main: return DispatchQueue.main
case .userInteractive: return DispatchQueue.global(qos: .userInteractive)
case .userInitiated: return DispatchQueue.global(qos: .userInitiated)
case .utility: return DispatchQueue.global(qos: .utility)
case .background: return DispatchQueue.global(qos: .background)
}
}
}
override func viewDidAppear(_ animated: Bool)
{
}
override func viewDidLoad()
{
super.viewDidLoad()
for i in 0..<20
{
delay(bySeconds: 1.0+Double(i)*0.5, dispatchLevel: .background)
{
print("__ \(i)")
// delayed code that will run on background thread
}
}
}
the actual output, notice the change of pattern after 10
__ 0
__ 1
__ 2
__ 3
__ 4
__ 5
__ 6
__ 7
__ 8
__ 9
__ 10
__ 12
__ 11
__ 14
__ 13
__ 16
__ 15
__ 17
__ 18
__ 19
the expected output
__ 0
__ 1
__ 2
__ 3
__ 4
__ 5
__ 6
__ 7
__ 8
__ 9
__ 10
__ 11
__ 12
__ 13
__ 14
__ 15
__ 16
__ 17
__ 18
__ 19
is there something wrong with the delay extension?