ios - 没有 '..<' 候选人产生预期的上下文结果类型 'NSRange Swift 3

标签 ios swift swift3

我已经迁移到 Swift 3.0,现在我在这一行收到错误:

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

No '..<' candidates produce the expected contextual result type 'NSRange' (aka '_NSRange') .我在这里做错了什么?

最佳答案

索引操作的语法已更改(请参阅 Get nth character of a string in Swift programming language 和完整的基本原理:Swift Evolution 0065):

let accountNumber = "XX0000000000000000001234"

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

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

无需在 Swift 中使用 NSStringNSRange

更简单的语法也是:

let lastFourDigits = accountNumber.substring(from: accountNumber.index(accountNumber.endIndex, offsetBy: -4))

关于ios - 没有 '..<' 候选人产生预期的上下文结果类型 'NSRange Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39752659/

相关文章:

ios - 如何在 iOS 应用程序中使 ScrollView 高度动态化?

iOS 构建因 IOException 而失败

ios - UITextView – 无法在文本上设置下划线或删除线属性?

ios - 定义一个可以在运行时在 View 之间切换的 Storyboard

swift - 在 UIView.Animate 中执行 2 CGAffineTransform - Swift

objective-c - Swift 框架到 Objective-C 设备和模拟器架构

Ios 可折叠和可展开的底板

swift - LLDB 中的自定义数据格式化程序

ios - UIcollectionView scrollToitemAtIndexPath 不适用于不可见的单元格

html - 如何将 HTML 格式和标签从 JSON url 引入 Swift 3