Skip to content

Instantly share code, notes, and snippets.

@rnapier
Last active April 13, 2018 01:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rnapier/bb6616871ed749542e542732c7386970 to your computer and use it in GitHub Desktop.
Save rnapier/bb6616871ed749542e542732c7386970 to your computer and use it in GitHub Desktop.
Random numbers in Swift
import Darwin
extension Integer {
static func makeRandomValue() -> Self {
var result: Self = 0
withUnsafeMutablePointer(&result) { resultPtr in
arc4random_buf(UnsafeMutablePointer(resultPtr), sizeof(Self.self))
}
return result
}
}
// From SE-0104 (just the bits I need)
public protocol FixedWidthInteger : Integer {
static var max: Self { get }
static var min: Self { get }
}
extension UInt64: FixedWidthInteger {}
extension Int64: FixedWidthInteger {}
extension UInt32: FixedWidthInteger {}
extension Int32: FixedWidthInteger {}
extension UInt16: FixedWidthInteger {}
extension Int16: FixedWidthInteger {}
extension UInt8: FixedWidthInteger {}
extension Int8: FixedWidthInteger {}
extension UInt: FixedWidthInteger {}
extension Int: FixedWidthInteger {}
extension FixedWidthInteger where Stride: SignedInteger { // Feels strange that I need this where clause
static func makeRandomValue(in range: CountableClosedRange<Self>) -> Self {
let rangeSize = range.upperBound - range.lowerBound
var randomValue = makeRandomValue()
let (s, overflow) = subtractWithOverflow(range.upperBound, range.lowerBound)
let maxDivisible = overflow ? max - ~s : s
while randomValue < maxDivisible {
randomValue = makeRandomValue()
}
return (randomValue % rangeSize) + range.lowerBound
}
}
UInt64.makeRandomValue(in: 5...6)
Int64.makeRandomValue(in: -10...10)
@fhorlaville
Copy link

fhorlaville commented Apr 2, 2017

Hi, I'm trying to use the popcount property, defined in FixedWidthInteger, and failing. I see you've managed to use FixedWidthInteger protocol and I'm trying to do the same but XCode 8.3 tells me

Value of type 'Int' has no member 'popcount' when I try

var n: Int = 20
answer = n.popcount

I tried mimicking what you did above:

import Darwin

public protocol FixedWidthInteger : Integer {
    var popcount: Int { get }
}

extension Int: FixedWidthInteger { }

but now I get: Type 'Int' does not conform to protocol 'FixedWidthInteger'

Would you have any suggestions?

Reference: http://swiftdoc.org/v3.1/protocol/FixedWidthInteger/

Thanks
Franck

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment