How does one generate a random number in Apple's Swift language?

后端 未结 25 1599
有刺的猬
有刺的猬 2020-11-22 09:51

I realize the Swift book provided an implementation of a random number generator. Is the best practice to copy and paste this implementation in one\'s own program? Or is t

相关标签:
25条回答
  • 2020-11-22 10:17

    Use arc4random_uniform(n) for a random integer between 0 and n-1.

    let diceRoll = Int(arc4random_uniform(6) + 1)
    

    Cast the result to Int so you don't have to explicitly type your vars as UInt32 (which seems un-Swifty).

    0 讨论(0)
  • 2020-11-22 10:17

    You can use GeneratorOf like this:

    var fibs = ArraySlice([1, 1])
    var fibGenerator = GeneratorOf{
        _ -> Int? in
        fibs.append(fibs.reduce(0, combine:+))
        return fibs.removeAtIndex(0)
    }
    
    println(fibGenerator.next())
    println(fibGenerator.next())
    println(fibGenerator.next())
    println(fibGenerator.next())
    println(fibGenerator.next())
    println(fibGenerator.next())
    
    0 讨论(0)
  • 2020-11-22 10:19

    You can do it the same way that you would in C:

    let randomNumber = arc4random()
    

    randomNumber is inferred to be of type UInt32 (a 32-bit unsigned integer)

    0 讨论(0)
  • 2020-11-22 10:20

    In Swift 4.2 you can generate random numbers by calling the random() method on whatever numeric type you want, providing the range you want to work with. For example, this generates a random number in the range 1 through 9, inclusive on both sides

    let randInt = Int.random(in: 1..<10)
    

    Also with other types

    let randFloat = Float.random(in: 1..<20)
    let randDouble = Double.random(in: 1...30)
    let randCGFloat = CGFloat.random(in: 1...40)
    
    0 讨论(0)
  • 2020-11-22 10:20

    Swift 4.2

    Swift 4.2 has included a native and fairly full-featured random number API in the standard library. (Swift Evolution proposal SE-0202)

    let intBetween0to9 = Int.random(in: 0...9) 
    let doubleBetween0to1 = Double.random(in: 0...1)
    

    All number types have the static random(in:) which takes the range and returns the random number in the given range

    0 讨论(0)
  • 2020-11-22 10:20

    Details

    xCode 9.1, Swift 4

    Math oriented solution (1)

    import Foundation
    
    class Random {
    
        subscript<T>(_ min: T, _ max: T) -> T where T : BinaryInteger {
            get {
                return rand(min-1, max+1)
            }
        }
    }
    
    let rand = Random()
    
    func rand<T>(_ min: T, _ max: T) -> T where T : BinaryInteger {
        let _min = min + 1
        let difference = max - _min
        return T(arc4random_uniform(UInt32(difference))) + _min
    }
    

    Usage of solution (1)

    let x = rand(-5, 5)       // x = [-4, -3, -2, -1, 0, 1, 2, 3, 4]
    let x = rand[0, 10]       // x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    

    Programmers oriented solution (2)

    Do not forget to add Math oriented solution (1) code here

    import Foundation
    
    extension CountableRange where Bound : BinaryInteger {
    
        var random: Bound {
            return rand(lowerBound-1, upperBound)
        }
    }
    
    extension CountableClosedRange where Bound : BinaryInteger {
    
        var random: Bound {
            return rand[lowerBound, upperBound]
        }
    }
    

    Usage of solution (2)

    let x = (-8..<2).random           // x = [-8, -7, -6, -5, -4, -3, -2, -1, 0, 1]
    let x = (0..<10).random           // x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    let x = (-10 ... -2).random       // x = [-10, -9, -8, -7, -6, -5, -4, -3, -2]
    

    Full Sample

    Do not forget to add solution (1) and solution (2) codes here

    private func generateRandNums(closure:()->(Int)) {
    
        var allNums = Set<Int>()
        for _ in 0..<100 {
            allNums.insert(closure())
        }
        print(allNums.sorted{ $0 < $1 })
    }
    
    generateRandNums {
        (-8..<2).random
    }
    
    generateRandNums {
        (0..<10).random
    }
    
    generateRandNums {
        (-10 ... -2).random
    }
    
    generateRandNums {
        rand(-5, 5)
    }
    generateRandNums {
        rand[0, 10]
    }
    

    Sample result

    0 讨论(0)
提交回复
热议问题