简体   繁体   中英

No '..<' candidates produce the expected contextual result type 'NSRange Swift 3

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?

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM