@@ -74,6 +74,51 @@ Swift 4.2
74
74
75
75
### 2018-09-17 (Xcode 10.0)
76
76
77
+ * [ SE-0202] [ ]
78
+
79
+ The standard library now provides a unified set of randomization functionality.
80
+ Integer types, floating point types, and Bool all introduce a new random
81
+ function.
82
+
83
+ ``` swift
84
+ let diceRoll = Int .random (in : 1 ... 6 )
85
+ let randomUnit = Double .random (in : 0 ..< 1 )
86
+ let randomBool = Bool .random ()
87
+ ```
88
+
89
+ There are also a couple of collection additions included as well.
90
+
91
+ ``` swift
92
+ let greetings = [" hey" , " hello" , " hi" , " hola" ]
93
+ let randomGreeting = greetings.randomElement ()! // This returns an Optional
94
+ let newGreetings = greetings.shuffled () // ["hola", "hi", "hey", "hello"]
95
+ ```
96
+
97
+ Core to the randomization functionality is a new ` RandomNumberGenerator `
98
+ protocol. The standard library defines its own random number generator
99
+ called ` SystemRandomNumberGenerator ` which is backed by a secure and thread
100
+ safe random number generator on each platform. All the randomization functions
101
+ have a ` using: ` parameter that take a ` RandomNumberGenerator ` that users can
102
+ pass in their own random number generator.
103
+
104
+ ``` swift
105
+ struct MersenneTwister : RandomNumberGenerator {
106
+ func next () -> UInt64 {
107
+ // Algorithm stuff here
108
+ }
109
+ }
110
+
111
+ var mt = MersenneTwister ()
112
+ let diceRoll = Int .random (in : 1 ... 6 , using : & mt)
113
+ let randomUnit = Double .random (in : 0 ..< 1 , & mt)
114
+ let randomBool = Bool .random (using : & mt)
115
+
116
+ // Collection additions
117
+ let greetings = [" hey" , " hello" , " hi" , " hola" ]
118
+ let randomGreeting = greetings.randomElement (using : & mt)! // This returns an Optional
119
+ let newGreetings = greetings.shuffled (using : & mt) // ["hola", "hi", "hey", "hello"]
120
+ ```
121
+
77
122
* [ SE-0194] [ ]
78
123
79
124
The new CaseIterable protocol describes types which have a static
0 commit comments