Search code examples
randomsrandswift3

What is the equivalent of seeded random in Swift3 (Xcode8 beta 1)


I need to start the same random number list over every execution of my app. srand/rand do not exist anymore. What should I do then?

private extension Array {
    private func randomValues(_ seed: UInt32, num: Int) -> [Element] {
        srand (seed)

        var indices = [Int]()
        indices.reserveCapacity(num)
        let range = 0..<self.count
        for _ in 0..<num {
            var random = 0
            repeat {
                random = randomNumberInRange(range)
            } while indices.contains(random)
            indices.append(random)
        }

        return indices.map { self[$0] }
    }

Solution

  • You can use srand48(seed) and drand48() in Swift3.