You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: proposals/0202-random-unification.md
+10-56Lines changed: 10 additions & 56 deletions
Original file line number
Diff line number
Diff line change
@@ -131,7 +131,7 @@ let randomBool2 = Bool.random(using: &myCustomRandomNumberGenerator)
131
131
132
132
#### Random Element
133
133
134
-
For `Collection` we add a random method with default implementation for collections to get a random element.
134
+
For `Collection` we add an extension method for collections to get a random element.
135
135
136
136
`Collection` example:
137
137
```swift
@@ -143,6 +143,13 @@ print(greetings.randomElement()!) // This returns an Optional
143
143
print(greetings.randomElement(using: &myCustomRandomNumberGenerator)!) // This returns an Optional
144
144
```
145
145
146
+
Note that some types make it easy to form collections with more elements than
147
+
can be represented as an `Int`, such as the range `Int.min...Int.max`, and
148
+
`randomElement` will likely trap on such collections. However, such ranges
149
+
are likely to trap when used with almost any collection API, and the
150
+
`random(in:)` method on `FixedWidthInteger` can be used for this purpose
151
+
instead.
152
+
146
153
#### Shuffle API
147
154
148
155
As a result of adding the random API, it only makes sense to utilize that power to fuel the shuffle methods. We extend `MutableCollection` to add a method to shuffle the collection itself, and extend `Sequence` to add a method to return a shuffled version of itself in a new array. Example:
@@ -199,14 +206,6 @@ public struct Random : RandomNumberGenerator {
199
206
publicmutatingfuncnext<T: FixedWidthInteger &UnsignedInteger>() -> T
200
207
}
201
208
202
-
publicprotocolCollection {
203
-
// Returns a random element from the collection
204
-
funcrandomElement<T: RandomNumberGenerator>(
205
-
usinggenerator: inout T
206
-
) ->Element?
207
-
}
208
-
209
-
// Default implementation
210
209
extensionCollection {
211
210
// Returns a random element from the collection
212
211
// Can return nil if isEmpty is true
@@ -220,52 +219,12 @@ extension Collection {
220
219
}
221
220
}
222
221
223
-
// We have to add this extension to support syntax like (Int.min ..< Int.max).random()
224
-
// That fails because Collection's implementation utilizes the count property and
225
-
// from Int.min to Int.max, an Int overflows with that big of a value.
226
-
extensionRange
227
-
where Bound :FixedWidthInteger,
228
-
Bound.Stride:SignedInteger,
229
-
Bound.Magnitude :UnsignedInteger {
230
-
// Returns a random element within lowerBound and upperBound
0 commit comments