2017-03-03 59 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就可以解決問題。