Generic Initializer

init(_:)

Creates a new string containing the characters in the given sequence.

Declaration

init<S>(_ characters: S) where S : Sequence, S.Element == Character

Parameters

characters

A string instance or another sequence of characters.

Discussion

You can use this initializer to create a new string from the result of one or more collection operations on a string’s characters. For example:

let str = "The rain in Spain stays mainly in the plain."

let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
let disemvoweled = String(str.lazy.filter { !vowels.contains($0) })

print(disemvoweled)
// Prints "Th rn n Spn stys mnly n th pln."

Relationships

See Also

Creating a String

init()

Creates an empty string.

init(Character)

Creates a string containing the given character.

init<S>(S)

Creates a new instance of a collection containing the elements of a sequence.

init<S>(S)

Creates a new string containing the characters in the given sequence.

init(Substring)

Creates a new string from the given substring.

init(repeating: String, count: Int)

Creates a new string representing the given string repeated the specified number of times.

init(repeating: Character, count: Int)

Creates a string representing the given character repeated the specified number of times.