What is the append(_:) string method in Swift?

Overview

The append(_:) method is used to append a string or character to another string.

Syntax

// append string
string.append(str)
// append character
string.append(char)

Parameters

  • string: This is the string we want to append to another string or character.

  • str: This is another string we want to append to the original string.

  • char: This is the character we want to append to string.

Return value

This method returns a new string containing the original string together with the appended string or character.

Example

// create strings
var str1 = "Edpre"
var str2 = ""
var str3 = "awe"
var str4 = ""
// append strings and characters
str1.append("sso")
str2.append("is")
str3.append("some")
str4.append("!")
// print results
print(str1)
print(str2)
print(str3)
print(str4)

Explanation

  • Lines 2 to 5: We create some string values.
  • Lines 8 to 11: We append some strings and characters to the strings we created using the append(_:) method.
  • Lines 14 to 17: We print the results.

Free Resources