was*_*dhu 2 string xcode ios swift
假设我有一个字符串,我想将该字符串中的第一个"a"更改为"e"以获得正确的拼写.
let animal = "elaphant"
使用stringByReplacingOccurrencesOfString()会将该字符串中的每个"a"更改为"e",返回:
elephent
我试图得到第一个"a"的索引,然后使用替换它replaceRange(),如下所示:
let index = animal.characters.indexOf("a")
let nextIndex = animal.startIndex.distanceTo(index!)
animal = animal.replaceRange(animal.startIndex.advancedBy(nextIndex)..<animal.startIndex.advancedBy(1), with: "e")
但是,此代码给出了以下错误:
Cannot assign value of type '()' to type 'String'
我一直试图找到一种方法将nextIndex转换为a Int,但我觉得我的整个方法都错了.救命?
这是你想要做的:
var animal = "elaphant"
if let range = animal.rangeOfString("a") {
  animal.replaceRange(range, with: "e")
}
rangeOfString 将搜索所提供的子字符串的第一个匹配项,如果找到该子字符串,它将返回一个可选范围,否则返回nil.
我们需要解开可选的,最安全的方法是使用if let语句,所以我们将范围分配给常量range.
意思是这样replaceRange做,在这种情况下我们需要animal成为一个var.
更新:
斯威夫特 4.2 或更高版本
var animal = "elaphant"
if let index = animal.firstIndex(of: "a") {
    animal.replaceSubrange(index...index, with: ["e"])
}
我们可以扩展RangeReplaceableCollection协议并创建我们自己的replaceFirstOccurrence(of: Element)方法:
extension RangeReplaceableCollection where Element: Equatable {
    mutating func replaceFirstOccurrence(of element: Element, with replacement: Element) {
        guard let index = firstIndex(of: element) else { return }
        replaceSubrange(index...index, with: CollectionOfOne(replacement))
    }
    func replacingFirstOccurrence(of element: Element, with replacement: Element) -> Self {
        var elements = self
        elements.replaceFirstOccurrence(of: element, with: replacement)
        return elements
    }
}
var animal = "elaphant"
// non mutating method
print(animal.replacingFirstOccurrence(of: "a", with: "e"))  // elephant
print(animal)     // still "elaphant"
// mutating method
animal.replaceFirstOccurrence(of: "a", with: "e")
print(animal)    // mutated to "elephant"