Structure

String

A Unicode string value.

Overview

A string is a series of characters, such as "Swift". Strings in Swift are Unicode correct, locale insensitive, and designed to be efficient. The String type bridges with the Objective-C class NSString and offers interoperability with C functions that works with strings.

You can create new strings using string literals or string interpolations. A string literal is a series of characters enclosed in quotes.

let greeting = "Welcome!"

String interpolations are string literals that evaluate any included expressions and convert the results to string form. String interpolations are an easy way to build a string from multiple pieces. Wrap each expression in a string interpolation in parentheses, prefixed by a backslash.

let name = "Rosa"
let personalizedGreeting = "Welcome, \(name)!"

let price = 2
let number = 3
let cookiePrice = "\(number) cookies: $\(price * number)."

Combine strings using the concatenation operator (+).

let longerGreeting = greeting + " We're glad you're here!"
print(longerGreeting)
// Prints "Welcome! We're glad you're here!"

Modifying and Comparing Strings

Strings always have value semantics. Modifying a copy of a string leaves the original unaffected.

var otherGreeting = greeting
otherGreeting += " Have a nice time!"
print(otherGreeting)
// Prints "Welcome! Have a nice time!"

print(greeting)
// Prints "Welcome!"

Comparing strings for equality using the equal-to operator (==) or a relational operator (like < and >=) is always performed using the Unicode canonical representation. This means that different representations of a string compare as being equal.

let cafe1 = "Cafe\u{301}"
let cafe2 = "Café"
print(cafe1 == cafe2)
// Prints "true"

The Unicode code point "\u{301}" modifies the preceding character to include an accent, so "e\u{301}" has the same canonical representation as the single Unicode code point "é".

Basic string operations are not sensitive to locale settings. This ensures that string comparisons and other operations always have a single, stable result, allowing strings to be used as keys in Dictionary instances and for other purposes.

Representing Strings: Views

A string is not itself a collection. Instead, it has properties that present its contents as meaningful collections. Each of these collections is a particular type of view of the string’s visible and data representation.

To demonstrate the different views available for every string, the following examples use this String instance:

let cafe = "Cafe\u{301} du 🌍"
print(cafe)
// Prints "Café du 🌍"

Character View

A string’s characters property is a collection of extended grapheme clusters, which approximate human-readable characters. Many individual characters, such as “é”, “김”, and “🇮🇳”, can be made up of multiple Unicode code points. These code points are combined by Unicode’s boundary algorithms into extended grapheme clusters, represented by Swift’s Character type. Each element of the characters view is represented by a Character instance.

print(cafe.characters.count)
// Prints "9"
print(Array(cafe.characters))
// Prints "["C", "a", "f", "é", " ", "d", "u", " ", "🌍"]"

Each visible character in the cafe string is a separate element of the characters view.

Unicode Scalar View

A string’s unicodeScalars property is a collection of Unicode scalar values, the 21-bit codes that are the basic unit of Unicode. Each scalar value is represented by a UnicodeScalar instance and is equivalent to a UTF-32 code unit.

print(cafe.unicodeScalars.count)
// Prints "10"
print(Array(cafe.unicodeScalars))
// Prints "["C", "a", "f", "e", "\u{0301}", " ", "d", "u", " ", "\u{0001F30D}"]"
print(cafe.unicodeScalars.map { $0.value })
// Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 127757]"

The unicodeScalars view’s elements comprise each Unicode scalar value in the cafe string. In particular, because cafe was declared using the decomposed form of the "é" character, unicodeScalars contains the code points for both the letter "e" (101) and the accent character "´" (769).

UTF-16 View

A string’s utf16 property is a collection of UTF-16 code units, the 16-bit encoding form of the string’s Unicode scalar values. Each code unit is stored as a UInt16 instance.

print(cafe.utf16.count)
// Prints "11"
print(Array(cafe.utf16))
// Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 55356, 57101]"

The elements of the utf16 view are the code units for the string when encoded in UTF-16.

The elements of this collection match those accessed through indexed NSString APIs.

let nscafe = cafe as NSString
print(nscafe.length)
// Prints "11"
print(nscafe.character(at: 3))
// Prints "101"

UTF-8 View

A string’s utf8 property is a collection of UTF-8 code units, the 8-bit encoding form of the string’s Unicode scalar values. Each code unit is stored as a UInt8 instance.

print(cafe.utf8.count)
// Prints "14"
print(Array(cafe.utf8))
// Prints "[67, 97, 102, 101, 204, 129, 32, 100, 117, 32, 240, 159, 140, 141]"

The elements of the utf8 view are the code units for the string when encoded in UTF-8. This representation matches the one used when String instances are passed to C APIs.

let cLength = strlen(cafe)
print(cLength)
// Prints "14"

Counting the Length of a String

When you need to know the length of a string, you must first consider what you’ll use the length for. Are you measuring the number of characters that will be displayed on the screen, or are you measuring the amount of storage needed for the string in a particular encoding? A single string can have greatly differing lengths when measured by its different views.

For example, an ASCII character like the capital letter A is represented by a single element in each of its four views. The Unicode scalar value of A is 65, which is small enough to fit in a single code unit in both UTF-16 and UTF-8.

let capitalA = "A"
print(capitalA.characters.count)
// Prints "1"
print(capitalA.unicodeScalars.count)
// Prints "1"
print(capitalA.utf16.count)
// Prints "1"
print(capitalA.utf8.count)
// Prints "1"

On the other hand, an emoji flag character is constructed from a pair of Unicode scalars values, like "\u{1F1F5}" and "\u{1F1F7}". Each of these scalar values, in turn, is too large to fit into a single UTF-16 or UTF-8 code unit. As a result, each view of the string "🇵🇷" reports a different length.

let flag = "🇵🇷"
print(flag.characters.count)
// Prints "1"
print(flag.unicodeScalars.count)
// Prints "2"
print(flag.utf16.count)
// Prints "4"
print(flag.utf8.count)
// Prints "8"

To check whether a string is empty, use its isEmpty property instead of comparing the length of one of the views to 0. Unlike isEmpty, calculating a view’s count property requires iterating through the elements of the string.

Accessing String View Elements

To find individual elements of a string, use the appropriate view for your task. For example, to retrieve the first word of a longer string, you can search the characters view for a space and then create a new string from a prefix of the characters view up to that point.

let name = "Marie Curie"
let firstSpace = name.characters.index(of: " ")!
let firstName = String(name.characters.prefix(upTo: firstSpace))
print(firstName)
// Prints "Marie"

You can convert an index into one of a string’s views to an index into another view.

let firstSpaceUTF8 = firstSpace.samePosition(in: name.utf8)
print(Array(name.utf8.prefix(upTo: firstSpaceUTF8)))
// Prints "[77, 97, 114, 105, 101]"

Performance Optimizations

Although strings in Swift have value semantics, strings use a copy-on-write strategy to store their data in a buffer. This buffer can then be shared by different copies of a string. A string’s data is only copied lazily, upon mutation, when more than one string instance is using the same buffer. Therefore, the first in any sequence of mutating operations may cost O(n) time and space.

When a string’s contiguous storage fills up, a new buffer must be allocated and data must be moved to the new storage. String buffers use an exponential growth strategy that makes appending to a string a constant time operation when averaged over many append operations.

Bridging between String and NSString

Any String instance can be bridged to NSString using the type-cast operator (as), and any String instance that originates in Objective-C may use an NSString instance as its storage. Because any arbitrary subclass of NSString can become a String instance, there are no guarantees about representation or efficiency when a String instance is backed by NSString storage. Because NSString is immutable, it is just as though the storage was shared by a copy: The first in any sequence of mutating operations causes elements to be copied into unique, contiguous storage which may cost O(n) time and space, where n is the length of the string’s encoded representation (or more, if the underlying NSString has unusual performance characteristics).

For more information about the Unicode terms used in this discussion, see the Unicode.org glossary. In particular, this discussion mentions extended grapheme clusters, Unicode scalar values, and canonical equivalence.

Nested Types

String.Encoding
String.CharacterView

A view of a string’s contents as a collection of characters.

String.UnicodeScalarView

A view of a string’s contents as a collection of Unicode scalar values.

String.UTF8View

A view of a string’s contents as a collection of UTF-8 code units.

String.UTF16View

A view of a string’s contents as a collection of UTF-16 code units.

Symbols

Type Aliases

CompareOptionsEncodingConversionOptionsEnumerationOptions
Index

The index type for subscripting a string.

IndexDistance

A type that represents the number of steps between two String.Index values, where one value is reachable from the other.

UTF16Index

The index type for subscripting a string’s utf16 view.

UTF8Index

The index type for subscripting a string’s utf8 view.

UnicodeScalarIndex

The index type for a string’s unicodeScalars view.

Initializers

init()

Creates an empty string.

init(NSString)
init(String.CharacterView)

Creates a string from the given character view.

init?(String)
init?(String.UTF16View)

Creates a string corresponding to the given sequence of UTF-16 code units.

init(Character)

Creates a string containing the given character.

init(String.UnicodeScalarView)

Creates a string corresponding to the given collection of Unicode scalars.

init?(String.UTF8View)

Creates a string corresponding to the given sequence of UTF-8 code units.

init<S>(S)

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

init<T>(T)

Creates an instance from the description of a given LosslessStringConvertible instance.

init<T>(T, radix: Int, uppercase: Bool)

Creates a string representing the given value in base 10, or some other specified base.

init<T>(T, radix: Int, uppercase: Bool)

Creates a string representing the given value in base 10, or some other specified base.

init?<S>(bytes: S, encoding: String.Encoding)

Produces an initialized NSString object equivalent to the given bytes interpreted in the given encoding.

init?(bytesNoCopy: UnsafeMutableRawPointer, length: Int, encoding: String.Encoding, freeWhenDone: Bool)

Produces an initialized String object that contains a given number of bytes from a given buffer of bytes interpreted in a given encoding, and optionally frees the buffer. WARNING: this initializer is not memory-safe!

init(cString: UnsafePointer<CChar>)

Creates a new string by copying the null-terminated UTF-8 data referenced by the given pointer.

init(cString: UnsafePointer<UInt8>)

Creates a new string by copying the null-terminated UTF-8 data referenced by the given pointer.

init?(cString: UnsafePointer<CChar>, encoding: String.Encoding)

Produces a string containing the bytes in a given C array, interpreted according to a given encoding.

init(contentsOf: URL)
init(contentsOf: URL, encoding: String.Encoding)

Produces a string created by reading data from a given URL interpreted using a given encoding. Errors are written into the inout error argument.

init(contentsOf: URL, usedEncoding: inout String.Encoding)

Produces a string created by reading data from a given URL and returns by reference the encoding used to interpret the data. Errors are written into the inout error argument.

init(contentsOfFile: String)
init(contentsOfFile: String, encoding: String.Encoding)

Produces a string created by reading data from the file at a given path interpreted using a given encoding.

init(contentsOfFile: String, usedEncoding: inout String.Encoding)

Produces a string created by reading data from the file at a given path and returns by reference the encoding used to interpret the file.

init?(data: Data, encoding: String.Encoding)

Returns a String initialized by converting given data into Unicode characters using a given encoding.

init<Subject>(describing: Subject)

Creates a string representing the given value.

init(extendedGraphemeClusterLiteral: String)

Creates an instance initialized to the given extended grapheme cluster literal.

init(format: String, CVarArg...)

Returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted.

init(format: String, arguments: [CVarArg])

Returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted according to the user’s default locale.

init(format: String, locale: Locale?, CVarArg...)

Returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted according to given locale information.

init(format: String, locale: Locale?, arguments: [CVarArg])

Returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted according to given locale information.

init<Subject>(reflecting: Subject)

Creates a string with a detailed representation of the given value, suitable for debugging.

init(repeating: String, count: Int)

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

init(stringInterpolation: String...)

Creates a new string by concatenating the given interpolations.

init(stringInterpolationSegment: String)

Creates a string containing the given value’s textual representation.

init(stringInterpolationSegment: Int16)

Creates a string containing the given value’s textual representation.

init(stringInterpolationSegment: UInt64)

Creates a string containing the given value’s textual representation.

init(stringInterpolationSegment: Int32)

Creates a string containing the given value’s textual representation.

init<T>(stringInterpolationSegment: T)

Creates a string containing the given expression’s textual representation.

init(stringInterpolationSegment: Float64)

Creates a string containing the given value’s textual representation.

init(stringInterpolationSegment: Int64)

Creates a string containing the given value’s textual representation.

init(stringInterpolationSegment: UnicodeScalar)

Creates a string containing the given value’s textual representation.

init(stringInterpolationSegment: Int)

Creates a string containing the given value’s textual representation.

init(stringInterpolationSegment: UInt)

Creates a string containing the given value’s textual representation.

init(stringInterpolationSegment: UInt32)

Creates a string containing the given value’s textual representation.

init(stringInterpolationSegment: Bool)

Creates a string containing the given value’s textual representation.

init(stringInterpolationSegment: Character)

Creates a string containing the given value’s textual representation.

init(stringInterpolationSegment: UInt8)

Creates a string containing the given value’s textual representation.

init(stringInterpolationSegment: UInt16)

Creates a string containing the given value’s textual representation.

init(stringInterpolationSegment: Float32)

Creates a string containing the given value’s textual representation.

init(stringInterpolationSegment: Int8)

Creates a string containing the given value’s textual representation.

init(stringLiteral: String)

Creates an instance initialized to the given string value.

init(unicodeScalarLiteral: String)

Creates an instance initialized to the given Unicode scalar value.

init(utf16CodeUnits: UnsafePointer<unichar>, count: Int)

Returns an initialized String object that contains a given number of characters from a given array of Unicode characters.

init(utf16CodeUnitsNoCopy: UnsafePointer<unichar>, count: Int, freeWhenDone: Bool)

Returns an initialized String object that contains a given number of characters from a given array of UTF-16 Code Units

init?(utf8String: UnsafePointer<CChar>)

Produces a string created by copying the data from a given C array of UTF8-encoded bytes.

init?(validatingUTF8: UnsafePointer<CChar>)

Creates a new string by copying and validating the null-terminated UTF-8 data referenced by the given pointer.

Instance Properties

var capitalized: String

Produce a string with the first character from each word changed to the corresponding uppercase value.

var characters: String.CharacterView

A view of the string’s contents as a collection of characters.

var customMirror: Mirror

A mirror that reflects the String instance.

var customPlaygroundQuickLook: PlaygroundQuickLook
var debugDescription: String

A representation of the string that is suitable for debugging.

var decomposedStringWithCanonicalMapping: String

Returns a string made by normalizing the String’s contents using Form D.

var decomposedStringWithCompatibilityMapping: String

Returns a string made by normalizing the String’s contents using Form KD.

var description: String
var endIndex: String.Index

A string’s “past the end” position—that is, the position one greater than the last valid subscript argument.

var fastestEncoding: String.Encoding

Returns the fastest encoding to which the String may be converted without loss of information.

var hash: Int

An unsigned integer that can be used as a hash table address.

var hashValue: Int

The string’s hash value.

var isEmpty: Bool

A Boolean value indicating whether a string has no characters.

var localizedCapitalized: String

A capitalized representation of the String that is produced using the current locale.

var localizedLowercase: String

A lowercase version of the string that is produced using the current locale.

var localizedUppercase: String

An uppercase version of the string that is produced using the current locale.

var precomposedStringWithCanonicalMapping: String

Returns a string made by normalizing the String’s contents using Form C.

var precomposedStringWithCompatibilityMapping: String

Returns a string made by normalizing the String’s contents using Form KC.

var removingPercentEncoding: String?

Returns a new string made from the String by replacing all percent encoded sequences with the matching UTF-8 characters.

var smallestEncoding: String.Encoding

Returns the smallest encoding to which the String can be converted without loss of information.

var startIndex: String.Index

The position of the first character in a nonempty string.

var unicodeScalars: String.UnicodeScalarView

The string’s value represented as a collection of Unicode scalar values.

var utf16: String.UTF16View

A UTF-16 encoding of self.

var utf8: String.UTF8View

A UTF-8 encoding of self.

var utf8CString: ContiguousArray<CChar>

A contiguously stored null-terminated UTF-8 representation of the string.

Type Properties

static var availableStringEncodings: [String.Encoding]

Returns an Array of the encodings string objects support in the application’s environment.

static var defaultCStringEncoding: String.Encoding

Returns the C-string encoding assumed for any method accepting a C string as an argument.

Instance Methods

func addingPercentEncoding(withAllowedCharacters: CharacterSet)

Returns a new string made from the String by replacing all characters not in the specified set with percent encoded characters.

func addingPercentEscapes(using: String.Encoding)

Returns a representation of the String using a given encoding to determine the percent escapes necessary to convert the String into a legal URL string.

Deprecated
func append(Character)

Appends the given character to the string.

func append(String)

Appends the given string to this string.

func append<S>(contentsOf: S)

Appends the characters in the given sequence to the string.

func appending(String)

Returns a new string made by appending a given string to the String.

func appendingFormat(String, CVarArg...)

Returns a string made by appending to the String a string constructed from a given format string and the following arguments.

func cString(using: String.Encoding)

Returns a representation of the String as a C string using a given encoding.

func canBeConverted(to: String.Encoding)

Returns a Boolean value that indicates whether the String can be converted to a given encoding without loss of information.

func capitalized(with: Locale?)

Returns a capitalized representation of the String using the specified locale.

func caseInsensitiveCompare(String)

Returns the result of invoking compare:options: with NSCaseInsensitiveSearch as the only option.

func commonPrefix(with: String, options: String.CompareOptions)

Returns a string containing characters the String and a given string have in common, starting from the beginning of each up to the first characters that aren’t equivalent.

func compare(String, options: String.CompareOptions, range: Range<String.Index>?, locale: Locale?)

Compares the string using the specified options and returns the lexical ordering for the range.

func completePath(into: UnsafeMutablePointer<String>?, caseSensitive: Bool, matchesInto: UnsafeMutablePointer<[String]>?, filterTypes: [String]?)

Interprets the String as a path in the file system and attempts to perform filename completion, returning a numeric value that indicates whether a match was possible, and by reference the longest path that matches the String. Returns the actual number of matching paths.

func components(separatedBy: CharacterSet)

Returns an array containing substrings from the String that have been divided by characters in a given set.

func components(separatedBy: String)

Returns an array containing substrings from the String that have been divided by a given separator.

func contains(String)

Returns true iff other is non-empty and contained within self by case-sensitive, non-literal search.

func data(using: String.Encoding, allowLossyConversion: Bool)

Returns a Data containing a representation of the String encoded using a given encoding.

func distance(from: String.Index, to: String.Index)

Returns the distance between two indices.

func folding(options: String.CompareOptions, locale: Locale?)

Returns a string with the given character folding options applied.

func getCString(inout [CChar], maxLength: Int, encoding: String.Encoding)

Converts the String’s content to a given encoding and stores them in a buffer.

func getParagraphStart(UnsafeMutablePointer<String.Index>, end: UnsafeMutablePointer<String.Index>, contentsEnd: UnsafeMutablePointer<String.Index>, for: Range<String.Index>)

Returns by reference the beginning of the first paragraph and the end of the last paragraph touched by the given range.

func hasPrefix(String)

Returns a Boolean value indicating whether the string begins with the specified prefix.

func hasSuffix(String)

Returns a Boolean value indicating whether the string ends with the specified suffix.

func index(String.Index, offsetBy: String.IndexDistance)

Returns an index that is the specified distance from the given index.

func index(String.Index, offsetBy: String.IndexDistance, limitedBy: String.Index)

Returns an index that is the specified distance from the given index, unless that distance is beyond a given limiting index.

func index(after: String.Index)

Returns the position immediately after the given index.

func index(before: String.Index)
func insert(Character, at: String.Index)

Inserts a new character at the specified position.

func insert<S>(contentsOf: S, at: String.Index)

Inserts a collection of characters at the specified position.

func lengthOfBytes(using: String.Encoding)

Returns the number of bytes required to store the String in a given encoding.

func lineRange(for: Range<String.Index>)

Returns the range of characters representing the line or lines containing a given range.

func localizedCaseInsensitiveCompare(String)

Compares the string and a given string using a case-insensitive, localized, comparison.

func localizedCaseInsensitiveContains(String)

Returns true iff other is non-empty and contained within self by case-insensitive, non-literal search, taking into account the current locale.

func localizedCompare(String)

Compares the string and a given string using a localized comparison.

func localizedStandardCompare(String)

Compares strings as sorted by the Finder.

func localizedStandardContains(String)

Returns true if self contains string, taking the current locale into account.

func localizedStandardRange(of: String)

Finds and returns the range of the first occurrence of a given string, taking the current locale into account. Returns nil if the string was not found.

func lowercased()

Returns a lowercase version of the string.

func lowercased(with: Locale?)

Returns a version of the string with all letters converted to lowercase, taking into account the specified locale.

func maximumLengthOfBytes(using: String.Encoding)

Returns the maximum number of bytes needed to store the String in a given encoding.

func padding(toLength: Int, withPad: String, startingAt: Int)

Returns a new string formed from the String by either removing characters from the end, or by appending as many occurrences as necessary of a given pad string.

func paragraphRange(for: Range<String.Index>)

Returns the range of characters representing the paragraph or paragraphs containing a given range.

func propertyList()

Parses the String as a text representation of a property list, returning an NSString, NSData, NSArray, or NSDictionary object, according to the topmost element.

func propertyListFromStringsFileFormat()

Returns a dictionary object initialized with the keys and values found in the String.

func range(of: String, options: String.CompareOptions, range: Range<String.Index>?, locale: Locale?)

Finds and returns the range of the first occurrence of a given string within a given range of the String, subject to given options, using the specified locale, if any.

func rangeOfCharacter(from: CharacterSet, options: String.CompareOptions, range: Range<String.Index>?)

Finds and returns the range in the String of the first character from a given character set found in a given range with given options.

func rangeOfComposedCharacterSequence(at: String.Index)

Returns the range in the String of the composed character sequence located at a given index.

func rangeOfComposedCharacterSequences(for: Range<String.Index>)

Returns the range in the string of the composed character sequences for a given range.

func remove(at: String.Index)

Removes and returns the character at the specified position.

func removeAll(keepingCapacity: Bool)

Replaces this string with the empty string.

func removeSubrange(Range<String.Index>)

Removes the characters in the given range.

func removeSubrange(ClosedRange<String.Index>)

Removes the characters in the given range.

func replaceSubrange(Range<String.Index>, with: String)

Replaces the text within the specified bounds with the given string.

func replaceSubrange<C>(Range<String.Index>, with: C)

Replaces the text within the specified bounds with the given characters.

func replaceSubrange<C>(ClosedRange<String.Index>, with: C)

Replaces the text within the specified bounds with the given characters.

func replaceSubrange(ClosedRange<String.Index>, with: String)

Replaces the text within the specified bounds with the given string.

func replacingCharacters(in: Range<String.Index>, with: String)

Returns a new string in which the characters in a specified range of the String are replaced by a given string.

func replacingOccurrences(of: String, with: String, options: String.CompareOptions, range: Range<String.Index>?)

Returns a new string in which all occurrences of a target string in a specified range of the String are replaced by another given string.

func replacingPercentEscapes(using: String.Encoding)

Returns a new string made by replacing in the String all percent escapes with the matching characters as determined by a given encoding.

Deprecated
func reserveCapacity(Int)

Reserves enough space in the string’s underlying storage to store the specified number of ASCII characters.

func substring(from: String.Index)

Returns a new string containing the characters of the String from the one at a given index to the end.

func substring(to: String.Index)

Returns a new string containing the characters of the String up to, but not including, the one at a given index.

func substring(with: Range<String.Index>)

Returns a string object containing the characters of the String that lie within a given range.

func trimmingCharacters(in: CharacterSet)

Returns a new string made by removing from both ends of the String characters contained in a given character set.

func uppercased()

Returns an uppercase version of the string.

func uppercased(with: Locale?)

Returns a version of the string with all letters converted to uppercase, taking into account the specified locale.

func withCString<Result>((UnsafePointer<Int8>) -> Result)

Invokes the given closure on the contents of the string, represented as a pointer to a null-terminated sequence of UTF-8 code units.

func withMutableCharacters<R>((inout String.CharacterView) -> R)

Applies the given closure to a mutable view of the string’s characters.

func write(String)

Appends the given string to this string.

func write<Target>(to: inout Target)

Writes the string into the given output stream.

func write(to: URL, atomically: Bool, encoding: String.Encoding)

Writes the contents of the String to the URL specified by url using the specified encoding.

func write(toFile: String, atomically: Bool, encoding: String.Encoding)

Writes the contents of the String to a file at a given path using a given encoding.

Type Methods

static func decodeCString<Encoding>(UnsafePointer<Encoding.CodeUnit>?, as: Encoding.Type, repairingInvalidCodeUnits: Bool)

Creates a new string by copying the null-terminated data referenced by the given pointer using the specified encoding.

static func localizedName(of: String.Encoding)

Returns a human-readable string giving the name of a given encoding.

static func localizedStringWithFormat(String, CVarArg...)

Returns a string created by using a given format string as a template into which the remaining argument values are substituted according to the user’s default locale.

Subscripts

subscript(Range<String.Index>)

Accesses the text in the given range.

subscript(String.Index)

Accesses the character at the given position.

subscript(ClosedRange<String.Index>)

Accesses the text in the given range.

See Also

Related Symbols

String.CharacterView, String.UnicodeScalarView, String.UTF16View, String.UTF8View