Last active
March 30, 2016 13:58
-
-
Save el-hoshino/060822ebfca34dd8a322151ccb683fba to your computer and use it in GitHub Desktop.
Range<Int> に distance 作って Int に指定範囲で乱数を作成させる extension ref: http://qiita.com/lovee/items/942de12e9edb5ad01f48
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//普通に distanceTo を使うからこの方法やめる | |
//extension Range where Element: IntegerType { | |
extension Range { | |
//普通に distanceTo を使うからこの方法やめる | |
//var distance: Element { | |
// return self.endIndex - self.startIndex | |
//} | |
var distance: Element.Distance { | |
return self.startIndex.distanceTo(self.endIndex) | |
} | |
} | |
extension Int { | |
static var random = {(range: Range<Int>) -> Int in | |
let distance = {(distance: Int) -> UInt32 in | |
guard distance <= Int(UInt32.max) else { | |
return UInt32.max | |
} | |
return UInt32(distance) | |
}(range.distance) | |
let randomUInt = arc4random_uniform(distance) | |
return Int(randomUInt) + range.startIndex | |
} | |
} | |
let a = Int.random(-127 ..< 128) | |
let b = Int.random(-127 ..< 128) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment