0

I've migrated to Swift 3.0 and I'm now getting an error on this line:

let lastFourDigits = (accountNumber as NSString).substringWithRange(accountNumber.endIndex.advancedBy(-4)..<accountNumber.endIndex)

No '..<' candidates produce the expected contextual result type 'NSRange' (aka '_NSRange'). What am I doing wrong here?

KexAri
  • 3,867
  • 6
  • 40
  • 80

1 Answers1

2

The syntax for index operations changed (see Get nth character of a string in Swift programming language and the full rationale: Swift Evolution 0065):

let accountNumber = "XX0000000000000000001234"

let lastFourDigits = accountNumber[accountNumber.index(accountNumber.endIndex, offsetBy: -4)..<accountNumber.endIndex]

print("Last 4: \(lastFourDigits)")

No need to use NSString or NSRange in Swift.

A simpler syntax would also be:

let lastFourDigits = accountNumber.substring(from: accountNumber.index(accountNumber.endIndex, offsetBy: -4))
Community
  • 1
  • 1
Sulthan
  • 128,090
  • 22
  • 218
  • 270