Skip to content

Commit 703c571

Browse files
author
Harlan Haskins
authored
Merge pull request #20320 from Azoy/random-readability
[QoI][stdlib] Improve some random call sites
2 parents 55076e2 + 309f46e commit 703c571

File tree

2 files changed

+5
-9
lines changed

2 files changed

+5
-9
lines changed

stdlib/public/core/Collection.swift

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -929,12 +929,9 @@ extension Collection {
929929
using generator: inout T
930930
) -> Element? {
931931
guard !isEmpty else { return nil }
932-
let random = generator.next(upperBound: UInt(count))
933-
let index = self.index(
934-
startIndex,
935-
offsetBy: numericCast(random)
936-
)
937-
return self[index]
932+
let random = Int.random(in: 0 ..< count, using: &generator)
933+
let idx = index(startIndex, offsetBy: random)
934+
return self[idx]
938935
}
939936

940937
/// Returns a random element of the collection.

stdlib/public/core/CollectionAlgorithms.swift

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -452,16 +452,15 @@ extension MutableCollection where Self : RandomAccessCollection {
452452
public mutating func shuffle<T: RandomNumberGenerator>(
453453
using generator: inout T
454454
) {
455-
let count = self.count
456455
guard count > 1 else { return }
457456
var amount = count
458457
var currentIndex = startIndex
459458
while amount > 1 {
460-
let random = generator.next(upperBound: UInt(amount))
459+
let random = Int.random(in: 0 ..< amount, using: &generator)
461460
amount -= 1
462461
swapAt(
463462
currentIndex,
464-
index(currentIndex, offsetBy: numericCast(random))
463+
index(currentIndex, offsetBy: random)
465464
)
466465
formIndex(after: &currentIndex)
467466
}

0 commit comments

Comments
 (0)