I am new to swift .. I am trying to crate delay and print the delay time like 1 seconds and start printing the next item into list . I got the result but I am not sure make delay of each iteration and print it .. Here is the struct .
struct CartProductResult {
var id: Int
var title: String
var quantity: Int
}
let cartProducts = [
CartProductResult(id: 1, title: "nike shoe 1", quantity: 5),
CartProductResult(id: 2, title: "nike shoe 2", quantity: 2),
CartProductResult(id: 3, title: "soap", quantity: 6)
]
Here is the function ..
func printWithDelay(product1: CartProductResult, product2:
CartProductResult, completion: (@escaping ()-> Void)) {
completion()
}
Here is the call to the function ..
printWithDelay(product1: cartProducts[0], product2: cartProducts[1])
{
let seconds = 1.0
DispatchQueue.main.asyncAfter(deadline: .now() seconds) {
print(" Wait 1 second")
for cartProduct in cartProducts {
print(cartProduct.id)
}
print("Done printing products")
}
}
Here is the expected result ..
CodePudding user response:
You do NOT want to use sleep()
on the main thread, as it will appear to "lock up" your app.
Instead, use a repeating Timer
-- try this, tap anywhere to start the printWithDelay()
:
class ViewController: UIViewController {
struct CartProductResult {
var id: Int
var title: String
var quantity: Int
}
let cartProducts = [
CartProductResult(id: 1, title: "nike shoe 1", quantity: 5),
CartProductResult(id: 2, title: "nike shoe 2", quantity: 2),
CartProductResult(id: 3, title: "soap", quantity: 6)
]
func printOneProduct(_ index: Int) {
let p = cartProducts[index]
print("id:", p.id)
}
func printWithDelay(products: [CartProductResult], completion: (@escaping ()-> Void)) {
var idx: Int = 0
// we want to print the first product immediately,
// then step through the rest 1-second at a time
printOneProduct(idx)
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
idx = 1
if idx == products.count {
timer.invalidate()
completion()
}
self.printOneProduct(idx)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
printWithDelay(products: cartProducts) {
print("Done printing products")
}
// execution continues while products are printing
}
}
CodePudding user response:
func printWithDelay(products: [CartProductResult], completion: (@escaping ()-> Void)) {
for product in products {
let seconds = 1.0
sleep(1)
print(" Wait 1 second")
print(product.id)
}
completion()
}
printWithDelay(products: cartProducts) {
print("Done printing products")
}