【问题标题】:No '..<' candidates produce the expected contextual result type 'NSRange Swift 3没有'..<' 候选产生预期的上下文结果类型'NSRange Swift 3
【发布时间】:2016-09-28 16:11:09
【问题描述】:

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

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

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

【问题讨论】:

  • let lastFourDigits = String(accountNumber.characters.suffix(4))

标签: ios swift swift3


【解决方案1】:

索引操作的语法已更改(请参阅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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多