2017-03-03 56 views
-1

我的下面代码崩溃:范围功能和崩溃在迅速3

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 
    } 

此代码与迅速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 
      } 
+0

什么是错误信息? – rmaddy

+1

你能提供更多的代码吗?因为我无法找到'utf16'从哪里来。在'String'的扩展中是这个函数的位置吗?请提供更多详细信息,以便我们可以帮助您。是的范围函数已经从Swift2更改了一些Swift3,Xcode自动转换总是无法正确转换它。 –

+0

@PangHoMing是的这些都是String扩展中的函数。 – user1452936

回答

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,最大位置你可以取代应该是8?

0

只需在代码中用unicodeScalars替换utf就可以解决问题。