如何在arc4random_uniform()的范围之间设置随机数?

时间:2021-01-25 13:28:13

so my goal in this codebit is to randomly roll two dice and as we all know your regular die only has 6 sides so I imported Foundation for access to arc4random_uniform(UInt32). I attempted using the range of (1..7) to avoid randomly getting 0 however that returned an error which I didn't enjoy too much. I tried to do this:

我在这个codebit的目标是随机掷两个骰子,我们都知道您的常规die只有6个面,所以我导入了Foundation来访问arc4random_uniform(UInt32)。我试图使用(1.. .7)的范围来避免随机得到0,但是这返回了一个我不太喜欢的错误。我试着这么做:

dice1 = arc4random_uniform(UInt32(1..7))

however that returned

然而,返回

Could not find an overload for 'init' that accepts the supplied arguments

无法找到接受提供的参数的“init”的重载?

I hope that this is enough information for you amazing debs out there to help me :)

我希望这对你们这些了不起的debs有足够的信息来帮助我:

Please note I am just doing this in a playground to practice swift. It isn't imperative that I learn how to do this; it's just me tinkering before I jump into building actual apps :D

请注意,我只是在操场上练习swift。我并不是一定要学会做这件事;在我开始构建真正的应用程序之前,我只是在修修补补:D

//imports random number function
import Foundation
//creates data storage for dice roll
var dice1: UInt32 = 0
var dice2: UInt32 = 0
//counter variable
var i = 0
//how many times snake eyes happens
var snakeeyes = 0
 //how many times a double is rolled
var `double` = 0
//rolls dice 100 times
while i < 100{
    //from here
    //sets dice roll

This returns an error of 'Range $T3' is not convertible to UInt32

这将返回一个“Range $T3”的错误,该错误不能转换为UInt32

   dice1 = arc4random_uniform(1..7)
   dice2 = arc4random_uniform(1..7)
    //checks for snake eyes
    if dice1 == 1 && dice2 == 1 {
        snakeeyes = snakeeyes + 1

    }
    //checks for doubles
    if dice1 == dice2{
        `double` = `double` + 1
    }
    //increases counter
        i = i + 1
    //to here
}
println("You got Snake Eyes \(snakeeyes) times.")
println("You got Doubles, \(`double`) times.")

17 个解决方案

#1


235  

I believe you should do

我认为你应该这么做

dice1 = arc4random_uniform(6) + 1;

to get the range 1 - 6. I don't do iOS objective C nor have I any knowledge on swift-language though. The random method should return a value between 0 and 5, and + 1 will make it a value between 1 and 6.

得到范围1 - 6。我不写iOS objective - C,也不懂swift语言。随机方法应该返回0到5之间的值,+ 1将使其成为1到6之间的值。

If you need a range between lets say 10 - 30 then just do

如果你需要一个介于10 - 30之间的范围,那就这么做

int random = arc4random_uniform(21) + 10;

#2


87  

I've made an Int type extension. tested it in playground, hope this is useful. It also accepts negative ranges:

我做了一个Int类型的扩展。在操场上测试过,希望这有用。它也接受负范围:

extension Int
{
    static func random(range: Range<Int> ) -> Int
    {
        var offset = 0

        if range.startIndex < 0   // allow negative ranges
        {
            offset = abs(range.startIndex)
        }

        let mini = UInt32(range.startIndex + offset)
        let maxi = UInt32(range.endIndex   + offset)

        return Int(mini + arc4random_uniform(maxi - mini)) - offset
    }
}

use like

使用像

var aRandomInt = Int.random(-500...100)  // returns a random number within the given range.

or define it as a Range extension as property like this:

或者将它定义为一个范围扩展为如下属性:

extension Range
{
    var randomInt: Int
    {
        get
        {
            var offset = 0

            if (startIndex as Int) < 0   // allow negative ranges
            {
                offset = abs(startIndex as Int)
            }

            let mini = UInt32(startIndex as Int + offset)
            let maxi = UInt32(endIndex   as Int + offset)

            return Int(mini + arc4random_uniform(maxi - mini)) - offset
        }
    }
}

// usage example: get an Int within the given Range:
let nr = (-1000 ... 1100).randomInt

#3


50  

Quite a few good answers, but I just wanted to share my personal favourite Swift random number generation function for positive integers:

有很多不错的答案,但我只想分享我个人最喜欢的正整数快速随机数生成函数:

Swift 2

func randomNumber(range: Range<Int> = 1...6) -> Int {
    let min = range.startIndex
    let max = range.endIndex
    return Int(arc4random_uniform(UInt32(max - min))) + min
}

Swift 3

Here's a quick update for Swift 3 and, as a bonus, it now works for any value type that conforms to the SignedInteger protocol - much more convenient for core data applications that need to specify Int16, Int32 etc. As a quick note, if you really need it to work on unsigned integers as well, just copy the entire function then replace SignedInteger with UnsignedInteger and toIntMax() with toUIntMax().

斯威夫特3和这里有一个快速更新,作为奖励,现在适用于任何值类型,符合SignedInteger协议——更方便核心数据的应用程序需要指定Int16 Int32等等。作为一个简短的说明,如果你真的需要它工作无符号整数,复制整个函数取代SignedInteger UnsignedInteger和toIntMax与toUIntMax()()。

func randomNumber<T : SignedInteger>(inRange range: ClosedRange<T> = 1...6) -> T {
    let length = (range.upperBound - range.lowerBound + 1).toIntMax()
    let value = arc4random().toIntMax() % length + range.lowerBound.toIntMax()
    return T(value)
}

Swift 4

Thanks to the removal of toIntMax() in Swift 4, we now have to use a different means of converting to a common integer type. In this example I'm using Int64 which is large enough for my purposes, but if you're using unsigned integers or have an Int128 or Int256 custom type you should use those.

由于在Swift 4中删除了toIntMax(),我们现在必须使用不同的方法来转换为通用整数类型。在本例中,我使用的是Int64,这对于我的目的来说已经足够大了,但是如果您使用的是无符号整数,或者使用的是Int128或Int256自定义类型,那么您应该使用它们。

public func randomNumber<T : SignedInteger>(inRange range: ClosedRange<T> = 1...6) -> T {
    let length = Int64(range.upperBound - range.lowerBound + 1)
    let value = Int64(arc4random()) % length + Int64(range.lowerBound)
    return T(value)
}

One more, for the total random-phile, here's an extension that returns a random element from any Collection type object. Note this uses the above function to generate its index so you will need both.

另外,对于所有的随机爱好者,这里有一个扩展,它从任何集合类型对象返回一个随机元素。注意,这使用了上面的函数来生成索引,因此您将需要这两个函数。

extension Collection {
    func randomItem() -> Self.Iterator.Element {
        let count = distance(from: startIndex, to: endIndex)
        let roll = randomNumber(inRange: 0...count-1)
        return self[index(startIndex, offsetBy: roll)]
    }
}

Usage

randomNumber()

returns a random number between 1 and 6.

返回1到6之间的随机数。

randomNumber(50...100)

returns a number between 50 and 100 inclusive. Naturally you can replace the values of 50 and 100 with whatever you like.

返回包含50到100的数字。当然,你可以用你喜欢的东西来替换50和100的值。

#4


17  

If You want i create that for random numbers. this is extension of number Int and Double, Float

如果你想要我为随机数创建它。这是数字Int和Double的扩展,浮点数

/**
    Arc Random for Double and Float
*/
public func arc4random <T: IntegerLiteralConvertible> (type: T.Type) -> T {
    var r: T = 0
    arc4random_buf(&r, UInt(sizeof(T)))
    return r
}
public extension Int {
    /**
    Create a random num Int
    :param: lower number Int
    :param: upper number Int
    :return: random number Int
    By DaRkDOG
    */
    public static func random (#lower: Int , upper: Int) -> Int {
        return lower + Int(arc4random_uniform(upper - lower + 1))
    }

}
public extension Double {
    /**
    Create a random num Double
    :param: lower number Double
    :param: upper number Double
    :return: random number Double
    By DaRkDOG
    */
    public static func random(#lower: Double, upper: Double) -> Double {
        let r = Double(arc4random(UInt64)) / Double(UInt64.max)
        return (r * (upper - lower)) + lower
    }
}
public extension Float {
    /**
    Create a random num Float
    :param: lower number Float
    :param: upper number Float
    :return: random number Float
    By DaRkDOG
    */
    public static func random(#lower: Float, upper: Float) -> Float {
        let r = Float(arc4random(UInt32)) / Float(UInt32.max)
        return (r * (upper - lower)) + lower
    }
}

USE :

使用:

let randomNumDouble = Double.random(lower: 0.00, upper: 23.50)
let randomNumInt = Int.random(lower: 56, upper: 992)
let randomNumInt =Float.random(lower: 6.98, upper: 923.09)

#5


11  

Swift 3/4:

func randomNumber(range: ClosedRange<Int> = 1...6) -> Int {
    let min = range.lowerBound
    let max = range.upperBound
    return Int(arc4random_uniform(UInt32(1 + max - min))) + min
}

#6


8  

That's because arc4random_uniform() is defined as follows:

这是因为arc4random_uniform()的定义如下:

func arc4random_uniform(_: UInt32) -> UInt32

It takes a UInt32 as input, and spits out a UInt32. You're attempting to pass it a range of values. arc4random_uniform gives you a random number in between 0 and and the number you pass it (exclusively), so if for example, you wanted to find a random number between -50 and 50, as in [-50, 50] you could use arc4random_uniform(101) - 50

它接受一个UInt32作为输入,并吐出一个UInt32。你试图传递一系列的值。arc4random_uniform给出的随机数介于0和传递给它的数字之间(独占),因此,如果您想要在-50到50之间找到一个随机数,如[- 50,50],您可以使用arc4random_uniform(101) -50

#7


5  

Swift:

迅速:

var index = 1 + random() % 6

#8


5  

I modified @DaRk-_-D0G's answer to work with Swift 2.0

我修改了@DaRk-_-D0G的答案,以配合Swift 2.0。

/**
Arc Random for Double and Float
*/
public func arc4random <T: IntegerLiteralConvertible> (type: T.Type) -> T {
    var r: T = 0
    arc4random_buf(&r, sizeof(T))
    return r
}
public extension Int {
    /**
    Create a random num Int
    :param: lower number Int
    :param: upper number Int
    :return: random number Int
    By DaRkDOG
    */
    public static func random (lower: Int , upper: Int) -> Int {
        return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
    }

}
public extension Double {
    /**
    Create a random num Double
    :param: lower number Double
    :param: upper number Double
    :return: random number Double
    By DaRkDOG
    */
    public static func random(lower: Double, upper: Double) -> Double {
        let r = Double(arc4random(UInt64)) / Double(UInt64.max)
        return (r * (upper - lower)) + lower
    }
}
public extension Float {
    /**
    Create a random num Float
    :param: lower number Float
    :param: upper number Float
    :return: random number Float
    By DaRkDOG
    */
    public static func random(lower: Float, upper: Float) -> Float {
        let r = Float(arc4random(UInt32)) / Float(UInt32.max)
        return (r * (upper - lower)) + lower
    }
}

#9


3  

In swift...

在迅速…

This is inclusive, calling random(1,2) will return a 1 or a 2, This will also work with negative numbers.

这是包容的,随机调用(1,2)会返回1或2,这也会用到负数。

    func random(min: Int, _ max: Int) -> Int {
        guard min < max else {return min}
        return Int(arc4random_uniform(UInt32(1 + max - min))) + min
    }

#10


3  

The answer is just 1 line code:

答案只有一行代码:

let randomNumber = arc4random_uniform(8999) + 1000 //for 4 digit random number
let randomNumber = arc4random_uniform(899999999) + 100000000 //for 9 digit random number
let randomNumber = arc4random_uniform(89) + 10    //for 2 digit random number
let randomNumber = arc4random_uniform(899) + 100  //for 3 digit random number

The alternate solution is:

替代解决方案是:

    func generateRandomNumber(numDigits: Int) -> Int{
    var place = 1
    var finalNumber = 0;
    var finanum = 0;
    for var i in 0 ..< numDigits {
        place *= 10
        let randomNumber = arc4random_uniform(10)         
        finalNumber += Int(randomNumber) * place
        finanum = finalNumber / 10
           i += 1
    }
    return finanum
}

Although the drawback is that number cannot start from 0.

虽然缺点是数字不能从0开始。

#11


1  

I successfully accomplished creating a random number using the following code:

我成功地使用以下代码创建了一个随机数:

var coin = arc4random_uniform(2) + 1

Hope this can help you.

希望这能对你有所帮助。

#12


1  

According to Swift 4.2 now it's easily to get random number like this

根据Swift 4.2,现在很容易得到这样的随机数

let randomDouble = Double.random(in: -7.9...12.8)

let randomIntFrom0To10 = Int.random(in: 0 ..< 10)

for more details check this out

要了解更多细节,请查看这里

#13


0  

Swift 3 Xcode Beta 5 Solution. Based on Ted van Gaalen Answer.

Swift 3 Xcode Beta 5解决方案。根据Ted van Gaalen的回答。

extension Int
  {
     static func random(range: Range<Int> ) -> Int
    {
        var offset = 0

        if range.lowerBound < 0   // allow negative ranges
        {
            offset = Swift.abs(range.lowerBound)
        }

        let mini = UInt32(range.lowerBound + offset)
        let maxi = UInt32(range.upperBound   + offset)

        return Int(mini + arc4random_uniform(maxi - mini)) - offset
    }
}

#14


0  

var rangeFromLimits = arc4random_uniform( (UPPerBound - LOWerBound) + 1)) + LOWerBound;

var rangeFromLimits = arc4random_uniform(上界-下界)+ 1)+下界;

#15


0  

Not sure why nobody else here extends Range:

不知道为什么这里没有人扩展范围:

public extension Range where Bound == Int {
    var random: Int {
        return lowerBound + Int(arc4random_uniform(UInt32(upperBound - lowerBound)))
    }
}

public extension ClosedRange where Bound == Int {
    var random: Int {
        return lowerBound + Int(arc4random_uniform(UInt32(upperBound - lowerBound + 1)))
    }
}

In use:

在使用:

let foo = (100..<600).random

#16


0  

hope this is working. make random number between range for arc4random_uniform()?

希望这是工作。使arc4random_uniform()的范围之间的随机数?

var randomNumber = Int(arc4random_uniform(6))
print(randomNumber)

#17


0  

Probably one find useful this a bit updated version of Range extension from Ted van Gaalen's answer using Swift 4/Xcode 9+:

可能有人会发现这是一个有用的一点更新版本的范围扩展从Ted van Gaalen的答案使用Swift 4/Xcode 9+:

extension CountableClosedRange where Bound == Int {
    var randomFromRange: Bound {
        get {
            var offset = 0
            if lowerBound < 0 {
                offset = abs(lowerBound)
            }
            let mini = UInt32(lowerBound + offset)
            let maxi = UInt32(upperBound + offset)
            return Int(mini + arc4random_uniform(maxi - mini)) - offset
        }
    }
}

let n = (-1000 ... 1000).randomFromRange
print(n)

Or this a bit "hacky" solution to support open and closed intervals:

或者这个有点“hacky”解决方案来支持开放和封闭间隔:

extension CountableRange where Bound == Int {
    var randomFromRange: Bound {
        return uniformRandom(from: lowerBound, to: upperBound)
    }
}

extension CountableClosedRange where Bound == Int {
    var randomFromRange: Bound {
        return uniformRandom(from: lowerBound, to: upperBound - 1)
    }
}

func uniformRandom(from: Int, to: Int) -> Int {
    var offset = 0
    if from < 0 {
        offset = abs(from)
    }
    let mini = UInt32(from + offset)
    let maxi = UInt32(to + offset)
    return Int(mini + arc4random_uniform(maxi - mini)) - offset
}

Not sure if there is a way to add property to both types of intervals simultaneously.

不确定是否有方法同时将属性添加到这两种间隔中。

#1


235  

I believe you should do

我认为你应该这么做

dice1 = arc4random_uniform(6) + 1;

to get the range 1 - 6. I don't do iOS objective C nor have I any knowledge on swift-language though. The random method should return a value between 0 and 5, and + 1 will make it a value between 1 and 6.

得到范围1 - 6。我不写iOS objective - C,也不懂swift语言。随机方法应该返回0到5之间的值,+ 1将使其成为1到6之间的值。

If you need a range between lets say 10 - 30 then just do

如果你需要一个介于10 - 30之间的范围,那就这么做

int random = arc4random_uniform(21) + 10;

#2


87  

I've made an Int type extension. tested it in playground, hope this is useful. It also accepts negative ranges:

我做了一个Int类型的扩展。在操场上测试过,希望这有用。它也接受负范围:

extension Int
{
    static func random(range: Range<Int> ) -> Int
    {
        var offset = 0

        if range.startIndex < 0   // allow negative ranges
        {
            offset = abs(range.startIndex)
        }

        let mini = UInt32(range.startIndex + offset)
        let maxi = UInt32(range.endIndex   + offset)

        return Int(mini + arc4random_uniform(maxi - mini)) - offset
    }
}

use like

使用像

var aRandomInt = Int.random(-500...100)  // returns a random number within the given range.

or define it as a Range extension as property like this:

或者将它定义为一个范围扩展为如下属性:

extension Range
{
    var randomInt: Int
    {
        get
        {
            var offset = 0

            if (startIndex as Int) < 0   // allow negative ranges
            {
                offset = abs(startIndex as Int)
            }

            let mini = UInt32(startIndex as Int + offset)
            let maxi = UInt32(endIndex   as Int + offset)

            return Int(mini + arc4random_uniform(maxi - mini)) - offset
        }
    }
}

// usage example: get an Int within the given Range:
let nr = (-1000 ... 1100).randomInt

#3


50  

Quite a few good answers, but I just wanted to share my personal favourite Swift random number generation function for positive integers:

有很多不错的答案,但我只想分享我个人最喜欢的正整数快速随机数生成函数:

Swift 2

func randomNumber(range: Range<Int> = 1...6) -> Int {
    let min = range.startIndex
    let max = range.endIndex
    return Int(arc4random_uniform(UInt32(max - min))) + min
}

Swift 3

Here's a quick update for Swift 3 and, as a bonus, it now works for any value type that conforms to the SignedInteger protocol - much more convenient for core data applications that need to specify Int16, Int32 etc. As a quick note, if you really need it to work on unsigned integers as well, just copy the entire function then replace SignedInteger with UnsignedInteger and toIntMax() with toUIntMax().

斯威夫特3和这里有一个快速更新,作为奖励,现在适用于任何值类型,符合SignedInteger协议——更方便核心数据的应用程序需要指定Int16 Int32等等。作为一个简短的说明,如果你真的需要它工作无符号整数,复制整个函数取代SignedInteger UnsignedInteger和toIntMax与toUIntMax()()。

func randomNumber<T : SignedInteger>(inRange range: ClosedRange<T> = 1...6) -> T {
    let length = (range.upperBound - range.lowerBound + 1).toIntMax()
    let value = arc4random().toIntMax() % length + range.lowerBound.toIntMax()
    return T(value)
}

Swift 4

Thanks to the removal of toIntMax() in Swift 4, we now have to use a different means of converting to a common integer type. In this example I'm using Int64 which is large enough for my purposes, but if you're using unsigned integers or have an Int128 or Int256 custom type you should use those.

由于在Swift 4中删除了toIntMax(),我们现在必须使用不同的方法来转换为通用整数类型。在本例中,我使用的是Int64,这对于我的目的来说已经足够大了,但是如果您使用的是无符号整数,或者使用的是Int128或Int256自定义类型,那么您应该使用它们。

public func randomNumber<T : SignedInteger>(inRange range: ClosedRange<T> = 1...6) -> T {
    let length = Int64(range.upperBound - range.lowerBound + 1)
    let value = Int64(arc4random()) % length + Int64(range.lowerBound)
    return T(value)
}

One more, for the total random-phile, here's an extension that returns a random element from any Collection type object. Note this uses the above function to generate its index so you will need both.

另外,对于所有的随机爱好者,这里有一个扩展,它从任何集合类型对象返回一个随机元素。注意,这使用了上面的函数来生成索引,因此您将需要这两个函数。

extension Collection {
    func randomItem() -> Self.Iterator.Element {
        let count = distance(from: startIndex, to: endIndex)
        let roll = randomNumber(inRange: 0...count-1)
        return self[index(startIndex, offsetBy: roll)]
    }
}

Usage

randomNumber()

returns a random number between 1 and 6.

返回1到6之间的随机数。

randomNumber(50...100)

returns a number between 50 and 100 inclusive. Naturally you can replace the values of 50 and 100 with whatever you like.

返回包含50到100的数字。当然,你可以用你喜欢的东西来替换50和100的值。

#4


17  

If You want i create that for random numbers. this is extension of number Int and Double, Float

如果你想要我为随机数创建它。这是数字Int和Double的扩展,浮点数

/**
    Arc Random for Double and Float
*/
public func arc4random <T: IntegerLiteralConvertible> (type: T.Type) -> T {
    var r: T = 0
    arc4random_buf(&r, UInt(sizeof(T)))
    return r
}
public extension Int {
    /**
    Create a random num Int
    :param: lower number Int
    :param: upper number Int
    :return: random number Int
    By DaRkDOG
    */
    public static func random (#lower: Int , upper: Int) -> Int {
        return lower + Int(arc4random_uniform(upper - lower + 1))
    }

}
public extension Double {
    /**
    Create a random num Double
    :param: lower number Double
    :param: upper number Double
    :return: random number Double
    By DaRkDOG
    */
    public static func random(#lower: Double, upper: Double) -> Double {
        let r = Double(arc4random(UInt64)) / Double(UInt64.max)
        return (r * (upper - lower)) + lower
    }
}
public extension Float {
    /**
    Create a random num Float
    :param: lower number Float
    :param: upper number Float
    :return: random number Float
    By DaRkDOG
    */
    public static func random(#lower: Float, upper: Float) -> Float {
        let r = Float(arc4random(UInt32)) / Float(UInt32.max)
        return (r * (upper - lower)) + lower
    }
}

USE :

使用:

let randomNumDouble = Double.random(lower: 0.00, upper: 23.50)
let randomNumInt = Int.random(lower: 56, upper: 992)
let randomNumInt =Float.random(lower: 6.98, upper: 923.09)

#5


11  

Swift 3/4:

func randomNumber(range: ClosedRange<Int> = 1...6) -> Int {
    let min = range.lowerBound
    let max = range.upperBound
    return Int(arc4random_uniform(UInt32(1 + max - min))) + min
}

#6


8  

That's because arc4random_uniform() is defined as follows:

这是因为arc4random_uniform()的定义如下:

func arc4random_uniform(_: UInt32) -> UInt32

It takes a UInt32 as input, and spits out a UInt32. You're attempting to pass it a range of values. arc4random_uniform gives you a random number in between 0 and and the number you pass it (exclusively), so if for example, you wanted to find a random number between -50 and 50, as in [-50, 50] you could use arc4random_uniform(101) - 50

它接受一个UInt32作为输入,并吐出一个UInt32。你试图传递一系列的值。arc4random_uniform给出的随机数介于0和传递给它的数字之间(独占),因此,如果您想要在-50到50之间找到一个随机数,如[- 50,50],您可以使用arc4random_uniform(101) -50

#7


5  

Swift:

迅速:

var index = 1 + random() % 6

#8


5  

I modified @DaRk-_-D0G's answer to work with Swift 2.0

我修改了@DaRk-_-D0G的答案,以配合Swift 2.0。

/**
Arc Random for Double and Float
*/
public func arc4random <T: IntegerLiteralConvertible> (type: T.Type) -> T {
    var r: T = 0
    arc4random_buf(&r, sizeof(T))
    return r
}
public extension Int {
    /**
    Create a random num Int
    :param: lower number Int
    :param: upper number Int
    :return: random number Int
    By DaRkDOG
    */
    public static func random (lower: Int , upper: Int) -> Int {
        return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
    }

}
public extension Double {
    /**
    Create a random num Double
    :param: lower number Double
    :param: upper number Double
    :return: random number Double
    By DaRkDOG
    */
    public static func random(lower: Double, upper: Double) -> Double {
        let r = Double(arc4random(UInt64)) / Double(UInt64.max)
        return (r * (upper - lower)) + lower
    }
}
public extension Float {
    /**
    Create a random num Float
    :param: lower number Float
    :param: upper number Float
    :return: random number Float
    By DaRkDOG
    */
    public static func random(lower: Float, upper: Float) -> Float {
        let r = Float(arc4random(UInt32)) / Float(UInt32.max)
        return (r * (upper - lower)) + lower
    }
}

#9


3  

In swift...

在迅速…

This is inclusive, calling random(1,2) will return a 1 or a 2, This will also work with negative numbers.

这是包容的,随机调用(1,2)会返回1或2,这也会用到负数。

    func random(min: Int, _ max: Int) -> Int {
        guard min < max else {return min}
        return Int(arc4random_uniform(UInt32(1 + max - min))) + min
    }

#10


3  

The answer is just 1 line code:

答案只有一行代码:

let randomNumber = arc4random_uniform(8999) + 1000 //for 4 digit random number
let randomNumber = arc4random_uniform(899999999) + 100000000 //for 9 digit random number
let randomNumber = arc4random_uniform(89) + 10    //for 2 digit random number
let randomNumber = arc4random_uniform(899) + 100  //for 3 digit random number

The alternate solution is:

替代解决方案是:

    func generateRandomNumber(numDigits: Int) -> Int{
    var place = 1
    var finalNumber = 0;
    var finanum = 0;
    for var i in 0 ..< numDigits {
        place *= 10
        let randomNumber = arc4random_uniform(10)         
        finalNumber += Int(randomNumber) * place
        finanum = finalNumber / 10
           i += 1
    }
    return finanum
}

Although the drawback is that number cannot start from 0.

虽然缺点是数字不能从0开始。

#11


1  

I successfully accomplished creating a random number using the following code:

我成功地使用以下代码创建了一个随机数:

var coin = arc4random_uniform(2) + 1

Hope this can help you.

希望这能对你有所帮助。

#12


1  

According to Swift 4.2 now it's easily to get random number like this

根据Swift 4.2,现在很容易得到这样的随机数

let randomDouble = Double.random(in: -7.9...12.8)

let randomIntFrom0To10 = Int.random(in: 0 ..< 10)

for more details check this out

要了解更多细节,请查看这里

#13


0  

Swift 3 Xcode Beta 5 Solution. Based on Ted van Gaalen Answer.

Swift 3 Xcode Beta 5解决方案。根据Ted van Gaalen的回答。

extension Int
  {
     static func random(range: Range<Int> ) -> Int
    {
        var offset = 0

        if range.lowerBound < 0   // allow negative ranges
        {
            offset = Swift.abs(range.lowerBound)
        }

        let mini = UInt32(range.lowerBound + offset)
        let maxi = UInt32(range.upperBound   + offset)

        return Int(mini + arc4random_uniform(maxi - mini)) - offset
    }
}

#14


0  

var rangeFromLimits = arc4random_uniform( (UPPerBound - LOWerBound) + 1)) + LOWerBound;

var rangeFromLimits = arc4random_uniform(上界-下界)+ 1)+下界;

#15


0  

Not sure why nobody else here extends Range:

不知道为什么这里没有人扩展范围:

public extension Range where Bound == Int {
    var random: Int {
        return lowerBound + Int(arc4random_uniform(UInt32(upperBound - lowerBound)))
    }
}

public extension ClosedRange where Bound == Int {
    var random: Int {
        return lowerBound + Int(arc4random_uniform(UInt32(upperBound - lowerBound + 1)))
    }
}

In use:

在使用:

let foo = (100..<600).random

#16


0  

hope this is working. make random number between range for arc4random_uniform()?

希望这是工作。使arc4random_uniform()的范围之间的随机数?

var randomNumber = Int(arc4random_uniform(6))
print(randomNumber)

#17


0  

Probably one find useful this a bit updated version of Range extension from Ted van Gaalen's answer using Swift 4/Xcode 9+:

可能有人会发现这是一个有用的一点更新版本的范围扩展从Ted van Gaalen的答案使用Swift 4/Xcode 9+:

extension CountableClosedRange where Bound == Int {
    var randomFromRange: Bound {
        get {
            var offset = 0
            if lowerBound < 0 {
                offset = abs(lowerBound)
            }
            let mini = UInt32(lowerBound + offset)
            let maxi = UInt32(upperBound + offset)
            return Int(mini + arc4random_uniform(maxi - mini)) - offset
        }
    }
}

let n = (-1000 ... 1000).randomFromRange
print(n)

Or this a bit "hacky" solution to support open and closed intervals:

或者这个有点“hacky”解决方案来支持开放和封闭间隔:

extension CountableRange where Bound == Int {
    var randomFromRange: Bound {
        return uniformRandom(from: lowerBound, to: upperBound)
    }
}

extension CountableClosedRange where Bound == Int {
    var randomFromRange: Bound {
        return uniformRandom(from: lowerBound, to: upperBound - 1)
    }
}

func uniformRandom(from: Int, to: Int) -> Int {
    var offset = 0
    if from < 0 {
        offset = abs(from)
    }
    let mini = UInt32(from + offset)
    let maxi = UInt32(to + offset)
    return Int(mini + arc4random_uniform(maxi - mini)) - offset
}

Not sure if there is a way to add property to both types of intervals simultaneously.

不确定是否有方法同时将属性添加到这两种间隔中。