范围函数和急速崩溃3

时间:2017-03-03 01:10:54

标签: swift range nsrange

我的下面的代码崩溃了:

func getrange(_ from: Int, length: Int) -> Range<String.Index>? {
    guard let fromU16 = utf16.index(utf16.startIndex, offsetBy: from, limitedBy: utf16.endIndex), fromU16 != utf16.endIndex else {
      return nil   ----->crashes here
    }
    let toU16 = utf16.index(fromU16, offsetBy: length, limitedBy: utf16.endIndex) ?? utf16.endIndex
    guard let from = String.Index(fromU16, within: self),
      let to = String.Index(toU16, within: self) else { return nil }
    return from ..< to
  }

此代码因swift 3迁移而崩溃。

有人可以帮助调试问题。

Below is the sequence of events:

     //input for below function is: text “123456789”, string “0”, nsrange = location =9, length=0

1)功能1

static func numericText(_ text: String, replacedBy string: String, in nsrange: NSRange) -> String {

            guard let range = text.range(for: nsrange) else {
              //assertionFailure("Should never reach here")
              return text.numericString()
            }

            // Apply Replacement String to the textField text and extract only the numeric values
            return text.replacingCharacters(in: range, with: string)
              .numericString()
          }

2)功能2

        func range(for nsrange: NSRange) -> Range<String.Index>? {
            return range(nsrange.location, length: nsrange.length)
          }

3)功能3

        func range(_ from: Int, length: Int) -> Range<String.Index>? {
            guard let fromU16 = utf16.index(utf16.startIndex, offsetBy: from, limitedBy: utf16.endIndex), fromU16 != utf16.endIndex else {
              return nil
            }
            let toU16 = utf16.index(fromU16, offsetBy: length, limitedBy: utf16.endIndex) ?? utf16.endIndex
            guard let from = String.Index(fromU16, within: self),
              let to = String.Index(toU16, within: self) else { return nil }
            return from ..< to
          }

2 个答案:

答案 0 :(得分:0)

抱歉,我没有在周末更新。 我回顾了你的问题。

我可以实现你的功能1:

extension String {
    func getrange(_ from: Int, length: Int) -> Range<String.Index>? {
        guard let fromU16 = utf16.index(utf16.startIndex, offsetBy: from, limitedBy: utf16.endIndex), fromU16 != utf16.endIndex else {
            return nil
        }
        let toU16 = utf16.index(fromU16, offsetBy: length, limitedBy: utf16.endIndex) ?? utf16.endIndex
        guard let from = String.Index(fromU16, within: self),
            let to = String.Index(toU16, within: self) else { return nil }
        return from ..< to
    }
}

但是我无法实现你的功能2,是否已转换为Swift3语法呢?

我的问题是这个,

Below is the sequence of events:

     //input for below function is: text “123456789”, string “0”, nsrange = location =9, length=0

您的输入,您的位置不应该是9.当您的字符串长度为9时,您可以替换的最大位置应为8?

答案 1 :(得分:0)

在代码中用unicodeScalars替换utf修复了这个问题。