NSMakeRange() to Range in Swift

Hello, I'm porting some of my old code to Swift and I'm running in to a little issue. I'm trying to get a range but I cant seem to get it all to work.


My old Obj-C code was


NSData *subData = [xData subdataWithRange:NSMakeRange(32, 16)];


I'm not sure how to convert this to Swift 5. half-open range operator wont go in reverse. I tried

.subdata(in: (16..<32).reverse() )


But that did not work.


Thanks!

Answered by Claude31 in 411578022

I assembled this toy code to show:


let string = "abcdefghij";
let data = string.data(using: String.Encoding.utf8)
let r = 2..<5
let data2 = Data((data!.subdata(in: r)).reversed())
let string2 = String(data: data2, encoding: String.Encoding.utf8)
print(string2!)

syntax is reversed()


.subdata(in: (16..<32).reversed () )

sorry, yes I tried reversed()


The error I get is ...


Cannot convert value of type 'ReversedCollection<(Range<Int>)>' to expected argument type 'Range<Data.Index>' (aka 'Range<Int>')

Accepted Answer

I assembled this toy code to show:


let string = "abcdefghij";
let data = string.data(using: String.Encoding.utf8)
let r = 2..<5
let data2 = Data((data!.subdata(in: r)).reversed())
let string2 = String(data: data2, encoding: String.Encoding.utf8)
print(string2!)

Awesome, thanks! I mis-read the docs on reversed(). I was under the impression that it returned the same data type.


Thanks again!

`NSMakeRange(32, 16)` makes a range of location: 32, length: 16. It does not mean something reversed.


The equivalent Swift code to your Objective-C code is:

var subData = xData.subdata(in: 32..<48)


Or, a little more simply:

var subData = xData[32..<48]


If your purpose is to convert your Objective-C code into Swift, `reversed` has nothing to do with it:

NSMakeRange() to Range in Swift
 
 
Q