This removes calls to `arc4random` and `arc4random_uniform` and replaces
them with calls to `Int.random` or equivalent.
These are a little less readable, which may be [why SwiftLint doesn't
like them][0]. (SwiftLint calls them "legacy", possibly because they're
not strong random number generators, but I couldn't find a clear
explanation for this anywhere, including [the original PR][1].)
This is the kind of change that's error-prone, so I wrote [a simple
script to help avoid regressions][2]. The script runs 10,000 iterations
of the old and new RNG and compares the ranges, reporting differences.
(Some differences are likely, like the ones that involve floats; others
are very unlikely to have differences.)
`git grep arc4random | grep swift` returns no results after this change.
Same for [everything else SwiftLint checks for][3].
[0]: https://realm.github.io/SwiftLint/legacy_random.html
[1]: https://github.com/realm/SwiftLint/pull/2419
[2]: https://gist.github.com/EvanHahn-Signal/9c75c9f484f4778149cbde3eafc9b285
[3]: ea6cc50890/Source/SwiftLintFramework/Rules/Idiomatic/LegacyRandomRule.swift (L23-L27)
26 lines
885 B
Swift
26 lines
885 B
Swift
//
|
|
// Copyright (c) 2022 Open Whisper Systems. All rights reserved.
|
|
//
|
|
|
|
import XCTest
|
|
|
|
class MathOWSTests: XCTestCase {
|
|
func testCGFloatRandom() throws {
|
|
let expectedTwoChoicesValues = Set([CGFloat(0), CGFloat(50)])
|
|
var actualTwoChoicesValues = Set<CGFloat>()
|
|
for _ in 1...1000 {
|
|
let value = CGFloat.random(in: 0..<100, choices: 2)
|
|
actualTwoChoicesValues.insert(value)
|
|
}
|
|
XCTAssertEqual(actualTwoChoicesValues, expectedTwoChoicesValues)
|
|
|
|
let expectedSixChoicesValues = Set([0, 0.25, 0.5, 0.75, 1, 1.25].map { CGFloat($0) })
|
|
var actualSixChoicesValues = Set<CGFloat>()
|
|
for _ in 1...10000 {
|
|
let value = CGFloat.random(in: 0..<1.5, choices: 6)
|
|
actualSixChoicesValues.insert(value)
|
|
}
|
|
XCTAssertEqual(actualSixChoicesValues, expectedSixChoicesValues)
|
|
}
|
|
}
|