Using the Range operator in Data.subdata

In Swift 3, I wonder why I can use the semi-open range operator ..< in Data.subdata (in :) , but not the closed range operator ...

I searched everywhere, but I can’t understand why this gives me this error: No candidates β€œ...” create the expected context result type 'Range' (aka 'Range')

Here is an example of one that works, and one that does not work:

 import Foundation let x = Data(bytes: [0x0, 0x1]) let y : UInt8 = x.subdata(in: 0..<2).withUnsafeBytes{$0.pointee} let z : UInt8 = x.subdata(in: 0...1).withUnsafeBytes{$0.pointee} // This fails 

Thanks!

+6
source share
2 answers
  • ..< is a semi-open statement that can either create a Range or CountableRange (depending on whether the Bound Strideable with Integer Stride or not). The range that is created includes the lower bound, but does not limit the upper bound.

  • ... is a closed range operator that can either create a ClosedRange or CountableClosedRange (same requirements as above). The created range includes both upper and lower bounds.

Therefore, since subdata(in:) expects a Range<Int> , you cannot use the closed range operator ... to construct an argument - you must use the half-open range operator.

However, it would be trivial to extend Data and add an overload that accepts a ClosedRange<Int> , which allows you to use a closed range operator.

 extension Data { func subdata(in range: ClosedRange<Index>) -> Data { return subdata(in: range.lowerBound ..< range.upperBound + 1) } } 

 let x = Data(bytes: [0x0, 0x1]) let z : UInt8 = x.subdata(in: 0...1).withUnsafeBytes {$0.pointee} 
+8
source
 import Foundation let x = Data(bytes: [0x0, 0x1]) let y : UInt8 = x.subdata(in: Range(0..<2)).withUnsafeBytes{$0.pointee} let z : UInt8 = x.subdata(in: Range(0...1)).withUnsafeBytes{$0.pointee} 
0
source

Source: https://habr.com/ru/post/1012047/


All Articles