2016-10-19 58 views
1

你們誰都知道要在Swift 3中使用stringByReplacingCharactersInRangeSwift 3:stringByReplacingCharactersInRange alternatives

我想轉換此Objective-CSwift

strToSort = [strToSort stringByReplacingCharactersInRange:NSMakeRange((i-1),1) withString: [strToSort substringWithRange:NSMakeRange((i),1)]]; 

我會很感激你的幫助。

回答

7

在Swift 3中。

strToSort = strToSort.replacingCharacters(in: range, with: str) 

注:這裏範圍是夫特Range<String.Index>對象不NSRange的類型。

欲瞭解更多有關Range的信息,請查詢Apple Documentation

例:

let str = "Apple" 
let i = 3 
let range = str.index(str.startIndex, offsetBy: i-1)..<str.index(str.startIndex, offsetBy: i) 
let subStringRange = str.index(str.startIndex, offsetBy: i)..<str.index(str.startIndex, offsetBy: i+1) 
print(str.replacingCharacters(in: range, with: str.substring(with: subStringRange))) 

輸出:

Aplle 
+0

我創建的範圍如下let rangeOne = strToSort.index(strToSort.startIndex,offsetBy:(i-1))。但我收到此錯誤:錯誤:無法將類型'String.Index'(又名'String.CharacterView.Index')的值轉換爲期望的參數類型'Range '(又名'Range ') – user2924482

+0

@ user2924482我不知道你已經問過如何製作範圍,但是昨天我不明白爲什麼有人投下了答案,然後我顯示了你的評論,所以我編輯了我的答案以後的參考。 –

-1

快捷方式,使用的NSString

let strToSort: NSString = "string to sort" let newString = strToSort.replacingCharacters(in: NSMakeRange(0, 6), with: "") print(newString) // to sort

希望它可以幫助