如何使用Swift生成范围(10 … 20)中的随机数

如何使用Swift生成范围(10 … 20)中的随机数,第1张

概述参见英文答案 > How does one generate a random number in Apple’s Swift language?                                    25个 我可以在我的游戏中为我的项目选择一个随机数,但是 是否有可能在2个数字之间选择一个随机数? 而不是 let number = (arc4random_uniform(100) 参见英文答案 > How does one generate a random number in Apple’s Swift language?                                    25个
我可以在我的游戏中为我的项目选择一个随机数,但是
是否有可能在2个数字之间选择一个随机数?

而不是

let number = (arc4random_uniform(100))

我想要这样的东西:

let number = (arc4random_uniform(10...20))

或类似的东西?
现在,如果我得到武器掉落,它可以是我列表中的所有内容.
通过这种方式,我可以做到这一点,只有前几个会对特定怪物有所下降,或者在更高级别,他们会丢弃更好的武器而不是低等级.

解决方法 Xcode 10•Swift 4.2

extension Range where Bound == Int {    var random: Int {        return Int.random(in: self)    }    func random(_ n: Int) -> [Int] {        return (0..<n).map { _ in random }    }}extension ClosedRange where Bound == Int {    var random: Int {        return Int.random(in: self)    }    func random(_ n: Int) -> [Int] {        return (0..<n).map { _ in random }    }}

Xcode 9•Swift 4

extension Range where Bound == Int {    var random: Int {        return lowerBound + numericCast(arc4random_uniform(numericCast(count)))    }    func random(_ n: Int) -> [Int] {        return (0..<n).map { _ in random }    }}extension ClosedRange where Bound == Int {    var random: Int {        return lowerBound + numericCast(arc4random_uniform(numericCast(count)))    }    func random(_ n: Int) -> [Int] {        return (0..<n).map { _ in random }    }}

Xcode 8.3.2•Swift 3.1

extension Range where Bound: StrIDeable,Bound == Int {    var random: Int {        return lowerBound + Int(arc4random_uniform(UInt32(count)))    }    func random(_ n: Int) -> [Int] {        return (0..<n).map { _ in random }    }}extension ClosedRange where Bound: StrIDeable,Bound == Int {    var random: Int {        return lowerBound + Int(arc4random_uniform(UInt32(count)))    }    func random(_ n: Int) -> [Int] {        return (0..<n).map { _ in random }    }}

用法:

(10...20).random    // 16(0...1).random(10)  // [0,1,0]
总结

以上是内存溢出为你收集整理的如何使用Swift生成范围(10 … 20)中的随机数全部内容,希望文章能够帮你解决如何使用Swift生成范围(10 … 20)中的随机数所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1009704.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存