【问题标题】:Swift 3: cannot convert value of type 'String.Index' to expected argument type Range (aka 'Range<String.CharacterView.Index>')Swift 3:无法将“String.Index”类型的值转换为预期的参数类型 Range(又名“Range<String.CharacterView.Index>”)
【发布时间】:2017-03-01 23:00:22
【问题描述】:

我正在尝试用另一个子字符串替换一个子字符串,但我收到了这个错误:

 cannot convert value of type 'String.Index' (aka 'String.CharacterView.Index') to expected argument type 'Range<String.Index>' (aka 'Range<String.CharacterView.Index>')

这是我的代码:

// This are the position of the substrings:
let rangeOne = strToSort.index(strToSort.startIndex, offsetBy: (i-1))
let rangeTwo = strToSort.index(strToSort.startIndex, offsetBy: (i))

Here is where I try to make the replacement:


strToSort = strToSort.replacingCharacters(in: rangeOne, with: strToSort.substring(with: rangeTwo))

但我收到此错误:

你们中的任何人都知道我做错了什么或解决这个问题吗?

非常感谢您的帮助

【问题讨论】:

  • 你想把EHLLOAGAIN改成HELLOAGAIN
  • var chars = "EHLLOAGAIN".characters.map{String($0)} swap(&amp;chars[0], &amp;chars[1])
  • @LeoDabus,但如何以编程方式进行。我的意思是如果在 x 位置切换子字符串,在 y 位置切换子字符串?

标签: string swift3 swift-playground


【解决方案1】:

像这样修改你的代码

var strToSort = "HELLOAGAIN"
let rangeOne = strToSort.index(strToSort.startIndex, offsetBy: (2))
let rangeTwo = strToSort.index(strToSort.startIndex, offsetBy: (3))
let stringRange = Range(uncheckedBounds: (lower: rangeOne, upper: rangeTwo))
strToSort = strToSort.replacingCharacters(in: stringRange, with: strToSort)
print(strToSort)

在您的代码中没有定义范围和方法 替换字符 需要类型的参数 Range&lt;String.Index&gt; 并且您提供的 String.Index 类型不正确,因此您遇到了错误。

如果你想用 E 替换像 H 这样的字符串,你可以使用不同的 String 方法,比如

let aString: String = "HELLO"
let newString = aString.stringByReplacingOccurrencesOfString("H", withString: "E", options: NSStringCompareOptions.LiteralSearch, range: nil)

【讨论】:

  • 如果我想将 H 替换为 E,如何管理范围。例如 EHLLOAGAIN?
  • 我要做的是替换字符串位置的子字符串基址而不是值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多