30

Is there any difference between:

NSRange(location: 0, length: 5)

and:

NSMakeRange(0, 5)

Because Swiftlint throws a warning when I use NSMakeRange, but I don't know why.

Thanks for the Help :-)

Forge
  • 6,538
  • 6
  • 44
  • 64
Auryn
  • 1,117
  • 1
  • 13
  • 37
  • 1
    Well for one of them, I know immediately what the values 0 and 5 represent without knowing anything about `NSRange`. – Hamish Jun 13 '17 at 13:20

2 Answers2

39

The only difference between them is that

NSRange(location: 0, length: 5)

is an initializer for NSRange while

NSMakeRange(0, 5)

is a function which creates a new NSRange instance (by using the same initializer inside most likely) and actually is redundant in Swift. Swift has simply inherited it from Objective-C. I would stick to the former

Andrey Chernukha
  • 21,488
  • 17
  • 97
  • 161
7

Main difference is that

NSRange(location: 0, length: 24) 

is auto-generated struct init method in Swift and

NSMakeRange(0, 24) 

is just a predefined macro that setts location and length

NS_INLINE NSRange NSMakeRange(NSUInteger loc, NSUInteger len) {
    NSRange r;
    r.location = loc;
    r.length = len;
    return r;
}

In general, result is the same, but if you're Swift use first one and if you're writing ObjC code use second ;)

zvjerka24
  • 1,772
  • 1
  • 21
  • 27