> On Oct 4, 2017, at 19:26, Xiaodi Wu via swift-evolution
> <[email protected]> wrote:
>
> extension Data {
> static func random(byteCount: Int) -> Data
> }
>
Instead of methods on specific concrete types, I’d prefer to have a Sequence or
Collection-conforming type that you could compose with existing operations like
init from a Sequence or replaceSubrange:
// Just a rough sketch...
struct RandomNumbers<T: FixedWidthInteger>: RandomAccessCollection {
let _range: ClosedRange<T>
let _count: Int
var startIndex: Int { return 0 }
var endIndex: Int { return _count }
subscript(i: Int) -> T { return _range.random() }
init(of: T.Type, count: Int) {
_range = T.min...T.max
_count = count
}
init(count: Int) {
self = RandomNumbers(of: T.self, count: count)
}
// possibly a constructor that takes a specific range
init<R: RangeExpression>(in: R, count: Int) where R.Bound == T {
// etc
}
}
for x in RandomNumbers(of: UInt8.self, count: 10) {
print(x)
}
let d = Data(RandomNumbers(count: 10))
var a = Array(0..<10)
a.replaceSubrange(5..., with: RandomNumbers(count: 5))
The tricky thing is that making it a Collection violates the (admittedly
unwritten) rule that a collection should be multi-pass, in the sense that
multiple passes produce different numbers. Then again, so can lazy collections
with impure closures. At least it isn’t variable length (unlike a lazy filter).
And making it a collection of defined size means it can be used efficiently
with things like append and replaceSubrange which reserve space in advance
_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution