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.
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) } } // ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With