8.4 C
Canberra
Saturday, July 26, 2025

ios – Swift async Loop in Job


I attempting to grasp how precisely Job works with loop.

I used to be experimenting with outputting numbers to the console and seen that I used to be getting a consequence that was not what I anticipated.

actor ThreadSafeCollection {
    personal var assortment: [T] = []

    func add(_ aspect: T) {
        assortment.append(aspect)
    }

    func getAll() -> [T] {
        return assortment
    }

    func take away(at index: Int) {
        guard assortment.indices.incorporates(index) else { return }
        assortment.take away(at: index)
    }
}

var safeCollection: ThreadSafeCollection = ThreadSafeCollection()

@Sendable func firstIterate() async -> Job<[Int], By no means> {
    Job {
        for i in 0..<500 {
            await safeCollection.add(i)
        }
        return await safeCollection.getAll()
    }
}

@Sendable func secondIterate() async -> Job<[Int], By no means> {
    Job {
        for i in 0..<500 {
            await safeCollection.add(i)
        }
        return await safeCollection.getAll()
    }
}

Job {
    let consequence = await withTaskGroup(of: [Int].self, returning: [Int].self) { taskGroup in
        taskGroup.addTask { await firstIterate().worth }
        taskGroup.addTask { await secondIterate().worth }
        
        var collected = [Int]()
        
        for await worth in taskGroup {
            collected.append(contentsOf: worth)
        }

        return collected
    }
    print(consequence.sorted(by: <))
}


On this instance, I iterate 2 instances to 500 by calling the primary Iterate() and secondIterate() strategies, because of which I anticipate to get an array with numbers during which every quantity shall be repeated 2 instances. However as an alternative, I see every quantity 4 instances within the console.
[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4...

And besides, I noticed that at the end of the array, the numbers are repeated not 4 times as at the beginning, but 3.

...494, 494, 494, 495, 495, 495, 496, 496, 496, 497, 497, 497, 498, 498, 498, 499, 499, 499]

Can anybody clarify why that is occurring?

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles