4 ms·
I've read a number of articles like this one regarding the Integer protocol in Swift and the many different int types: http://blog.krzyzanowskim.com/2015/03/01
by hellofunk 11y ago
I've read a number of articles like this one regarding the Integer protocol in Swift and the many different int types:
http://blog.krzyzanowskim.com/2015/03/01/swift_madness_of_generic_integer/ http://blog.krzyzanowskim.com/2015/03/01/swift_madness_of_ge...
I guess everyone's mileage varies, but I find it a bit strange.
- eridius 11y agoThe only thing strange is that the author of the post seems to be trying to make Swift's integer handling sound unnecessarily complex. > There are 11 Integer types that can be considered as Integers Although he's including Bit which doesn't really count (it conforms to the appropriate protocols but from the doc comment you can see it's actually just intended as the index type for CollectionOfOne). But having a bunch of different integer types shouldn't be surprising. Every integer type Swift has corresponds to an integer type in C, e.g. Int16 is int16_t, UInt64, is uint64_t, Int is long, etc. As for the protocols, so what? It's a bad thing that most of the functionality of integers can be represented using a bunch of protocols? Clearly not. All the author is trying to do is make things sound complex. > My goal here is to create generic function that will handle any integer value and make some operation on it. In this case I want to build function that get bytes and return integer value build with the given bytes array of bytes So he wants to have a function that builds integer types all different sizes given an array of bytes, and wants to do it generically for any integer? Ok, take a pointer to your bytes, cast it to a pointer to integers of the right size, and you're done. Oh wait.. he wants to do it without "raw memory", whatever that means? That's stupid. The rest of the article is nothing but a complicated exercise in trying to do things as hard as possible. His entire function can be written in pure Swift (without NSData) as func integerWithBytes<T: IntegerType>(bytes: [UInt8]) -> T? { guard bytes.count >= sizeof(T) else { return nil } return bytes.withUnsafeBufferPointer({ UnsafePointer<T>($0.baseAddress).memory }) } That's it. 100% pure Swift, and probably about as efficient as you can get.