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

后端 未结 25 2074
有刺的猬
有刺的猬 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:20

    Details

    xCode 9.1, Swift 4

    Math oriented solution (1)

    import Foundation
    
    class Random {
    
        subscript(_ min: T, _ max: T) -> T where T : BinaryInteger {
            get {
                return rand(min-1, max+1)
            }
        }
    }
    
    let rand = Random()
    
    func rand(_ 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()
        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

提交回复
热议问题