Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding to a String in Swift 4

I was wondering the best way to add to a String in Swift 4. Did Apple create a better way than stringName.characters.append(“hi”)

Edit: Noted below which I never knew you used to be able to use a String.append(). I was trying to get at the fact that in Swift 4 you don't have to use .characters anymore. I was trying to help out new people to swift 4 by making a question that they might ask so that they can save time by not using .characters after a String variable.

like image 443
the_kaseys Avatar asked Sep 15 '25 15:09

the_kaseys


1 Answers

You can invoke append(_:) directly on the String instance:

var stringName = ""
stringName.append("hi")
print(stringName) // hi
stringName.append(" John")
print(stringName) // hi John

Likewise, you can use the += operator of String for the concatenation

var stringName = ""
stringName += "hi"
print(stringName) // hi
stringName += " John"
print(stringName) // hi John

For the curious one, the implementation of both of these approaches make use of the same backend (/core) append(...) call. Quoting swift/stdlib/public/core/String.swift:

extension String {

  // ...

  public mutating func append(_ other: String) {
    _core.append(other._core)
  }

  // ...
}

extension String {

  // ...

  public static func += (lhs: inout String, rhs: String) {
    if lhs.isEmpty {
      lhs = rhs
    }
    else {
      lhs._core.append(rhs._core)
    }
  }

  // ...
}
like image 74
dfrib Avatar answered Sep 18 '25 09:09

dfrib