How to Append a Character to a String in Swift

How to append a character to a string in Swift?

Update for the moving target that is Swift:

Swift no longer has a + operator that can take a String and an array of characters. (There is a string method appendContentsOf() that can be used for this purpose).

The best way of doing this now is Martin R’s answer in a comment below:

var newStr:String = str + String(aCharacter)

Original answer:
This changed in Beta 6. Check the release notes.I'm still downloading it, but try using:

var newStr:String = str + [aCharacter]

Append Character to String in Swift

20140818, Apple updated:

Updated the Concatenating Strings and Characters section to reflect the fact that String and Character values can no longer be combined with the addition operator (+) or addition assignment operator (+=). These operators are now used only with String values. Use the String type’s append method to append a single Character value onto the end of a string.

Document Revision History 2014-08-18

Adding to a String in Swift 4

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)
}
}

// ...
}

Fastest, leanest way to append characters to form a string in Swift

(This answer was written based on documentation and source code valid for Swift 2 and 3: possibly needs updates and amendments once Swift 4 arrives)

Since Swift is now open-source, we can actually have a look at the source code for Swift:s native String

  • swift/stdlib/public/core/String.swift

From the source above, we have following comment

/// Growth and Capacity
/// ===================
///
/// When a string's contiguous storage fills up, new storage must be
/// allocated and characters must be moved to the new storage.
/// `String` uses an exponential growth strategy that makes `append` a
/// constant time operation *when amortized over many invocations*.

Given the above, you shouldn't need to worry about the performance of appending characters in Swift (be it via append(_: Character), append(_: UniodeScalar) or appendContentsOf(_: String)), as reallocation of the contiguous storage for a certain String instance should not be very frequent w.r.t. number of single characters needed to be appended for this re-allocation to occur.

Also note that NSMutableString is not "purely native" Swift, but belong to the family of bridged Obj-C classes (accessible via Foundation).


A note to your comment

"I thought that String was immutable, but I noticed its append method returns Void."

String is just a (value) type, that may be used by mutable as well as immutable properties

var foo = "foo" // mutable 
let bar = "bar" // immutable
/* (both the above inferred to be of type 'String') */

The mutating void-return instance methods append(_: Character) and append(_: UniodeScalar) are accessible to mutable as well as immutable String instances, but naturally using them with the latter will yield a compile time error

let chars : [Character]  = ["b","a","r"]
foo.append(chars[0]) // "foob"
bar.append(chars[0]) // error: cannot use mutating member on immutable value ...

Add string to beginning of another string

Re. your basic question:

 secondString = "\(firstString)\(secondString)"

or

secondString = firstString + secondString

Here is a way to insert string at the beginning "without resetting" per your comment (first at front of second):

let range = second.startIndex..<second.startIndex
second.replaceRange(range, with: first)

Re. your "more detail" question:

var fullString: String

if second == "00" {
fullString = third + fourth
} else if first == "00" {
fullString = second + third + fourth
} else {
fullString = first + second + third + fourth
}

How to add a character at a particular index in string in Swift

If you are declaring it as NSMutableString then it is possible and you can do it this way:

let str: NSMutableString = "3022513240)"
str.insert("(", at: 0)
print(str)

The output is :

(3022513240)

EDIT:

If you want to add at starting:

var str = "3022513240)"
str.insert("(", at: str.startIndex)

If you want to add character at last index:

str.insert("(", at: str.endIndex)

And if you want to add at specific index:

str.insert("(", at: str.index(str.startIndex, offsetBy: 2))

Append String in Swift

Its very simple:

For ObjC:

     NSString *string1 = @"This is";
NSString *string2 = @"Swift Language";

ForSwift:

    let string1 = "This is"
let string2 = "Swift Language"

For ObjC AppendString:

     NSString *appendString=[NSString stringWithFormat:@"%@ %@",string1,string2];

For Swift AppendString:

    var appendString1 = "\(string1) \(string2)"
var appendString2 = string1+string2

Result:

    print("APPEND STRING 1:\(appendString1)")
print("APPEND STRING 2:\(appendString2)")

Complete Code In Swift:

    let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
print("APPEND STRING1:\(appendString1)")
print("APPEND STRING2:\(appendString2)")

Swift 3: append characters to an Array

You need to be using the append(contentsOf:) method instead.

foo.append(contentsOf: text.characters.map { String($0) })

This method can take an array of the defined type.

Whereas the append() method expects a single element to add at the end of the array.

Swift 3 string insert

label.insert("9", ind:2)

For index, you need to provide the index, not integer.

 // to insert at 0 position
let str = label.text!;
label.text!.insert("9", at:str.startIndex);

or

// to insert at 2nd position
label.text!.insert("9", at: str.index(str.startIndex, offsetBy: 2)) ;


Related Topics



Leave a reply



Submit