Swift replace first character in string

Swift 4 or later

let string = "&whatever"
let output = "?" + string.dropFirst()

mutating the string

var string = "&whatever"
if !string.isEmpty {
    string.replaceSubrange(...string.startIndex, with: "?")
    print(string)  // "?whatever\n"
}

You can try this:

var s = "123456"

let s2 = s.replacingCharacters(in: ...s.startIndex, with: "a")

s2 // "a23456"

let range = Range(start: query.startIndex, end: query.startIndex.successor())
query.replaceRange(range, with: "?")

or shorter

let s = query.startIndex
query.replaceRange(s...s, with: "?")

This is a bit different from Objective-C - but we will get used to it I guess ;-).

If you are uncomfortable with this, you can always drop back to the old NSString APIs:

let newQuery = (query as NSString).stringByReplacingCharactersInRange(
  NSMakeRange(0,1), withString: "?") // as String not necessary

Tags:

Ios

Swift