String

struct String

An arbitrary Unicode string value.

Unicode-Correct

Swift strings are designed to be Unicode-correct. In particular, the APIs make it easy to write code that works correctly, and does not surprise end-users, regardless of where you venture in the Unicode character space. For example, the == operator checks for Unicode canonical equivalence, so two different representations of the same string will always compare equal.

Locale-Insensitive

The fundamental operations on Swift strings are not sensitive to locale settings. That's because, for example, the validity of a Dictionary<String, T> in a running program depends on a given string comparison having a single, stable result. Therefore, Swift always uses the default, un-tailored Unicode algorithms for basic string operations.

Importing Foundation endows swift strings with the full power of the NSString API, which allows you to choose more complex locale-sensitive operations explicitly.

Value Semantics

Each string variable, let binding, or stored property has an independent value, so mutations to the string are not observable through its copies:

var a = "foo"
var b = a
b.appendContentsOf("bar")
print("a=\(a), b=\(b)")     // a=foo, b=foobar

Strings use Copy-on-Write so that their 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, where N is the length of the string's (unspecified) underlying representation.

Views

String is not itself a collection of anything. Instead, it has properties that present the string's contents as meaningful collections:

characters: a collection of Character (extended grapheme cluster) elements, a unit of text that is meaningful to most humans.

unicodeScalars: a collection of UnicodeScalar (Unicode scalar values) the 21-bit codes that are the basic unit of Unicode. These values are equivalent to UTF-32 code units.

utf16: a collection of UTF16.CodeUnit, the 16-bit elements of the string's UTF-16 encoding.

utf8: a collection of UTF8.CodeUnit, the 8-bit elements of the string's UTF-8 encoding.

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.

Objective-C Bridge

String is bridged to Objective-C as NSString, and a String that originated in Objective-C may store its characters in an NSString. Since any arbitrary subclass of NSString can become a String, there are no guarantees about representation or efficiency in this case. Since NSString is immutable, it is just as though the storage was shared by some 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 representation (or more, if the underlying NSString has unusual performance characteristics).

Inheritance Comparable, CustomDebugStringConvertible, Equatable, ExtendedGraphemeClusterLiteralConvertible, Hashable, MirrorPathType, OutputStreamType, Streamable, StringInterpolationConvertible, StringLiteralConvertible, UnicodeScalarLiteralConvertible, _ObjectiveCBridgeable, _Reflectable View Protocol Hierarchy →
Associated Types
Index = String.CharacterView.Index
UnicodeScalarIndex = String.UnicodeScalarView.Index

The index type for subscripting a String's .unicodeScalars view.

UTF16Index = String.UTF16View.Index

The index type for subscripting a String's utf16 view.

UTF8Index = String.UTF8View.Index

The index type for subscripting a String's .utf8 view.

Nested Types String.CharacterView, String.UnicodeScalarView, String.UTF16View, String.UTF8View, String.CharacterView.Index, String.UnicodeScalarView.Index, String.UnicodeScalarView.Generator, String.UTF16View.Index, String.UTF8View.Index
Import import Swift

Initializers

init()

An empty String.

Declaration

init()
init(_: Character)

Construct an instance containing just the given Character.

Declaration

init(_ c: Character)
init(_: NSString)

[Foundation]

Declaration

init(_ cocoaString: NSString)
init(_: String.CharacterView)

Construct the String corresponding to the given sequence of Unicode scalars.

Declaration

init(_ characters: String.CharacterView)
init(_: String.UnicodeScalarView)

Construct the String corresponding to the given sequence of Unicode scalars.

Declaration

init(_ unicodeScalars: String.UnicodeScalarView)
init<T>(_: T)

Initialize self with the textual representation of instance.

  • If T conforms to Streamable, the result is obtained by calling instance.writeTo(s) on an empty string s.
  • Otherwise, if T conforms to CustomStringConvertible, the result is instance's description
  • Otherwise, if T conforms to CustomDebugStringConvertible, the result is instance's debugDescription
  • Otherwise, an unspecified result is supplied automatically by the Swift standard library.

See Also: String.init<T>(reflecting: T)

Declaration

init<T>(_ instance: T)
init<T : _SignedIntegerType>(_: T)

Create an instance representing v in base 10.

Declaration

init<T : _SignedIntegerType>(_ v: T)
init<T : UnsignedIntegerType>(_: T)

Create an instance representing v in base 10.

Declaration

init<T : UnsignedIntegerType>(_ v: T)
init<S : SequenceType where S.Generator.Element == Character>(_: S)

Create an instance containing characters.

Declaration

init<S : SequenceType where S.Generator.Element == Character>(_ characters: S)
init<T : _SignedIntegerType>(_: T, radix: Int, uppercase: Bool)

Create an instance representing v in the given radix (base).

Numerals greater than 9 are represented as roman letters, starting with a if uppercase is false or A otherwise.

Declaration

init<T : _SignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default)
init<T : UnsignedIntegerType>(_: T, radix: Int, uppercase: Bool)

Create an instance representing v in the given radix (base).

Numerals greater than 9 are represented as roman letters, starting with a if uppercase is false or A otherwise.

Declaration

init<T : UnsignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default)
init(_builtinExtendedGraphemeClusterLiteral:byteSize:isASCII:)

Declaration

init(_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1)
init(_builtinStringLiteral:byteSize:isASCII:)

Declaration

init(_builtinStringLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1)
init(_builtinUTF16StringLiteral:numberOfCodeUnits:)

Declaration

init(_builtinUTF16StringLiteral start: Builtin.RawPointer, numberOfCodeUnits: Builtin.Word)
init(_builtinUnicodeScalarLiteral:)

Declaration

init(_builtinUnicodeScalarLiteral value: Builtin.Int32)
init(contentsOfFile:encoding:)

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

Declaration

init(contentsOfFile path: String, encoding enc: NSStringEncoding)
init(contentsOfFile:usedEncoding:)

[Foundation] 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.

Declaration

init(contentsOfFile path: String, usedEncoding: UnsafeMutablePointer<NSStringEncoding> = default)
init(contentsOfURL:encoding:)

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

Declaration

init(contentsOfURL url: NSURL, encoding enc: NSStringEncoding)
init(contentsOfURL:usedEncoding:)

[Foundation] 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.

Declaration

init(contentsOfURL url: NSURL, usedEncoding enc: UnsafeMutablePointer<NSStringEncoding> = default)
init(count: Int, repeatedValue: Character)

Construct an instance that is the concatenation of count copies of repeatedValue.

Declaration

init(count: Int, repeatedValue c: Character)
init(count: Int, repeatedValue: UnicodeScalar)

Construct an instance that is the concatenation of count copies of Character(repeatedValue).

Declaration

init(count: Int, repeatedValue c: UnicodeScalar)
init(extendedGraphemeClusterLiteral:)

Create an instance initialized to value.

Declaration

init(extendedGraphemeClusterLiteral value: String)
init(format:_:)

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

Declaration

init(format: String, _ arguments: CVarArgType...)
init(format:arguments:)

[Foundation] 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.

Declaration

init(format: String, arguments: [CVarArgType])
init(format:locale:_:)

[Foundation] 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.

Declaration

init(format: String, locale: NSLocale?, _ args: CVarArgType...)
init(format:locale:arguments:)

[Foundation] 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.

Declaration

init(format: String, locale: NSLocale?, arguments: [CVarArgType])
init(reflecting:)

Initialize self with a detailed textual representation of subject, suitable for debugging.

  • If T conforms to CustomDebugStringConvertible, the result is subject's debugDescription.

  • Otherwise, if T conforms to CustomStringConvertible, the result is subject's description.

  • Otherwise, if T conforms to Streamable, the result is obtained by calling subject.writeTo(s) on an empty string s.

  • Otherwise, an unspecified result is supplied automatically by the Swift standard library.

See Also: String.init<T>(T)

Declaration

init<T>(reflecting subject: T)
init(stringInterpolation:)

Create an instance by concatenating the elements of strings.

Declaration

init(stringInterpolation strings: String...)
init(stringInterpolationSegment: Bool)

Declaration

init(stringInterpolationSegment expr: Bool)
init(stringInterpolationSegment: Character)

Declaration

init(stringInterpolationSegment expr: Character)
init(stringInterpolationSegment: Float32)

Declaration

init(stringInterpolationSegment expr: Float32)
init(stringInterpolationSegment: Float64)

Declaration

init(stringInterpolationSegment expr: Float64)
init(stringInterpolationSegment: Int)

Declaration

init(stringInterpolationSegment expr: Int)
init(stringInterpolationSegment: Int8)

Declaration

init(stringInterpolationSegment expr: Int8)
init(stringInterpolationSegment: Int16)

Declaration

init(stringInterpolationSegment expr: Int16)
init(stringInterpolationSegment: Int32)

Declaration

init(stringInterpolationSegment expr: Int32)
init(stringInterpolationSegment: Int64)

Declaration

init(stringInterpolationSegment expr: Int64)
init(stringInterpolationSegment: String)

Declaration

init(stringInterpolationSegment expr: String)
init(stringInterpolationSegment: UInt)

Declaration

init(stringInterpolationSegment expr: UInt)
init(stringInterpolationSegment: UInt8)

Declaration

init(stringInterpolationSegment expr: UInt8)
init(stringInterpolationSegment: UInt16)

Declaration

init(stringInterpolationSegment expr: UInt16)
init(stringInterpolationSegment: UInt32)

Declaration

init(stringInterpolationSegment expr: UInt32)
init(stringInterpolationSegment: UInt64)

Declaration

init(stringInterpolationSegment expr: UInt64)
init(stringInterpolationSegment: UnicodeScalar)

Declaration

init(stringInterpolationSegment expr: UnicodeScalar)
init<T>(stringInterpolationSegment: T)

Create an instance containing expr's print representation.

Declaration

init<T>(stringInterpolationSegment expr: T)
init(stringLiteral:)

Create an instance initialized to value.

Declaration

init(stringLiteral value: String)
init(unicodeScalarLiteral:)

Create an instance initialized to value.

Declaration

init(unicodeScalarLiteral value: String)
init(utf16CodeUnits:count:)

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

Declaration

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

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

Declaration

init(utf16CodeUnitsNoCopy: UnsafePointer<unichar>, count: Int, freeWhenDone flag: Bool)
init?(_: String.UTF8View)

Construct the String corresponding to the given sequence of UTF-8 code units. If utf8 contains unpaired surrogates, the result is nil.

Declaration

init?(_ utf8: String.UTF8View)
init?(_: String.UTF16View)

Construct the String corresponding to the given sequence of UTF-16 code units. If utf16 contains unpaired surrogates, the result is nil.

Declaration

init?(_ utf16: String.UTF16View)
init?(CString:encoding:)

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

Declaration

init?(CString: UnsafePointer<CChar>, encoding enc: NSStringEncoding)
init?(UTF8String:)

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

Declaration

init?(UTF8String bytes: UnsafePointer<CChar>)
init?(bytes:encoding:)

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

Declaration

init?<S : SequenceType where S.Generator.Element == UInt8>(bytes: S, encoding: NSStringEncoding)
init?(bytesNoCopy:length:encoding:freeWhenDone:)

[Foundation] 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!

Declaration

init?(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int, encoding: NSStringEncoding, freeWhenDone flag: Bool)
init?(data:encoding:)

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

Declaration

init?(data: NSData, encoding: NSStringEncoding)

Instance Variables

var capitalizedString: String

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

Declaration

var capitalizedString: String { get }
var characters: String.CharacterView

A collection of Characters representing the String's extended grapheme clusters.

Declaration

var characters: String.CharacterView { get }
var debugDescription: String

A textual representation of self, suitable for debugging.

Declaration

var debugDescription: String { get }
var decomposedStringWithCanonicalMapping: String

[Foundation] Returns a string made by normalizing the String’s

contents using Form D.

Declaration

var decomposedStringWithCanonicalMapping: String { get }
var decomposedStringWithCompatibilityMapping: String

[Foundation] Returns a string made by normalizing the String’s

contents using Form KD.

Declaration

var decomposedStringWithCompatibilityMapping: String { get }
var endIndex: Index

The "past the end" position in self.characters.

endIndex is not a valid argument to subscript, and is always reachable from startIndex by zero or more applications of successor().

Declaration

var endIndex: Index { get }
var fastestEncoding: NSStringEncoding

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

Declaration

var fastestEncoding: NSStringEncoding { get }
var hash: Int

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

Declaration

var hash: Int { get }
var hashValue: Int

The hash value.

Axiom: x == y implies x.hashValue == y.hashValue.

Note: The hash value is not guaranteed to be stable across different invocations of the same program. Do not persist the hash value across program runs.

Declaration

var hashValue: Int { get }
var isEmpty: Bool

true iff self contains no characters.

Declaration

var isEmpty: Bool { get }
var localizedCapitalizedString: String

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

Declaration

var localizedCapitalizedString: String { get }
var localizedLowercaseString: String

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

Declaration

var localizedLowercaseString: String { get }
var localizedUppercaseString: String

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

Declaration

var localizedUppercaseString: String { get }
var lowercaseString: String

Declaration

var lowercaseString: String { get }
var nulTerminatedUTF8: ContiguousArray<CodeUnit>

A contiguously-stored nul-terminated UTF-8 representation of self.

To access the underlying memory, invoke withUnsafeBufferPointer on the ContiguousArray.

Declaration

var nulTerminatedUTF8: ContiguousArray<CodeUnit> { get }
var precomposedStringWithCanonicalMapping: String

[Foundation] Returns a string made by normalizing the String’s

contents using Form C.

Declaration

var precomposedStringWithCanonicalMapping: String { get }
var precomposedStringWithCompatibilityMapping: String

[Foundation] Returns a string made by normalizing the String’s

contents using Form KC.

Declaration

var precomposedStringWithCompatibilityMapping: String { get }
var smallestEncoding: NSStringEncoding

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

Declaration

var smallestEncoding: NSStringEncoding { get }
var startIndex: Index

The position of the first Character in self.characters if self is non-empty; identical to endIndex otherwise.

Declaration

var startIndex: Index { get }
var stringByRemovingPercentEncoding: String?

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

Declaration

var stringByRemovingPercentEncoding: String? { get }
var unicodeScalars: String.UnicodeScalarView

The value of self as a collection of Unicode scalar values.

Declaration

var unicodeScalars: String.UnicodeScalarView { get set }
var uppercaseString: String

Declaration

var uppercaseString: String { get }
var utf8: String.UTF8View

A UTF-8 encoding of self.

Declaration

var utf8: String.UTF8View { get }
var utf16: String.UTF16View

A UTF-16 encoding of self.

Declaration

var utf16: String.UTF16View { get }

Subscripts

subscript(_: Index)

Access the Character at position.

Requires: position is a valid position in self.characters and position != endIndex.

Declaration

subscript(i: Index) -> Character { get }
subscript(_: Range<Index>)

Access the characters in the given subRange.

Complexity: O(1) unless bridging from Objective-C requires an O(N) conversion.

Declaration

subscript(subRange: Range<Index>) -> String { get }

Static Methods

static func availableStringEncodings()

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

Declaration

static func availableStringEncodings() -> [NSStringEncoding]
static func defaultCStringEncoding()

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

Declaration

static func defaultCStringEncoding() -> NSStringEncoding
static func fromCString(_:)

Creates a new String by copying the nul-terminated UTF-8 data referenced by a CString.

Returns nil if the CString is NULL or if it contains ill-formed UTF-8 code unit sequences.

Declaration

static func fromCString(cs: UnsafePointer<CChar>) -> String?
static func fromCStringRepairingIllFormedUTF8(_:)

Creates a new String by copying the nul-terminated UTF-8 data referenced by a CString.

Returns nil if the CString is NULL. If CString contains ill-formed UTF-8 code unit sequences, replaces them with replacement characters (U+FFFD).

Declaration

static func fromCStringRepairingIllFormedUTF8(cs: UnsafePointer<CChar>) -> (String?, hadError: Bool)
static func localizedNameOfStringEncoding(_:)

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

Declaration

static func localizedNameOfStringEncoding(encoding: NSStringEncoding) -> String
static func localizedStringWithFormat(_:_:)

[Foundation] 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.

Declaration

static func localizedStringWithFormat(format: String, _ arguments: CVarArgType...) -> String

Instance Methods

mutating func append(_: Character)

Declaration

mutating func append(c: Character)
mutating func append(_: UnicodeScalar)

Append x to self.

Complexity: Amortized O(1).

Declaration

mutating func append(x: UnicodeScalar)
mutating func appendContentsOf(_: String)

Append the elements of other to self.

Declaration

mutating func appendContentsOf(other: String)
mutating func appendContentsOf<S : SequenceType where S.Generator.Element == Character>(_: S)

Declaration

mutating func appendContentsOf<S : SequenceType where S.Generator.Element == Character>(newElements: S)
func cStringUsingEncoding(_:)

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

Declaration

func cStringUsingEncoding(encoding: NSStringEncoding) -> [CChar]?
func canBeConvertedToEncoding(_:)

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

Declaration

func canBeConvertedToEncoding(encoding: NSStringEncoding) -> Bool
func capitalizedStringWithLocale(_:)

[Foundation] Returns a capitalized representation of the String using the specified locale.

Declaration

func capitalizedStringWithLocale(locale: NSLocale?) -> String
func caseInsensitiveCompare(_:)

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

Declaration

func caseInsensitiveCompare(aString: String) -> NSComparisonResult
func commonPrefixWithString(_:options:)

[Foundation] 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.

Declaration

func commonPrefixWithString(aString: String, options: NSStringCompareOptions) -> String
func compare(_:options:range:locale:)

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

Declaration

func compare(aString: String, options mask: NSStringCompareOptions = default, range: Range<Index>? = default, locale: NSLocale? = default) -> NSComparisonResult
func completePathIntoString(_:caseSensitive:matchesIntoArray:filterTypes:)

[Foundation] 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.

Declaration

func completePathIntoString(outputName: UnsafeMutablePointer<String> = default, caseSensitive: Bool, matchesIntoArray: UnsafeMutablePointer<[String]> = default, filterTypes: [String]? = default) -> Int
func componentsSeparatedByCharactersInSet(_:)

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

Declaration

func componentsSeparatedByCharactersInSet(separator: NSCharacterSet) -> [String]
func componentsSeparatedByString(_:)

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

Declaration

func componentsSeparatedByString(separator: String) -> [String]
func containsString(_:)

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

Equivalent to self.rangeOfString(other) != nil

Declaration

func containsString(other: String) -> Bool
func dataUsingEncoding(_:allowLossyConversion:)

[Foundation] Returns an NSData object containing a representation of the String encoded using a given encoding.

Declaration

func dataUsingEncoding(encoding: NSStringEncoding, allowLossyConversion: Bool = default) -> NSData?
func enumerateLines(_:)

[Foundation] Enumerates all the lines in a string.

Declaration

func enumerateLines(body: (line: String, inout stop: Bool) -> ())
func enumerateLinguisticTagsInRange(_:scheme:options:orthography:_:)

[Foundation] Performs linguistic analysis on the specified string by enumerating the specific range of the string, providing the Block with the located tags.

Declaration

func enumerateLinguisticTagsInRange(range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTaggerOptions, orthography: NSOrthography?, _ body: (String, Range<Index>, Range<Index>, inout Bool) -> ())
func enumerateSubstringsInRange(_:options:_ body: (substring: String?, substringRange: Range<Index>,:)

[Foundation] Enumerates the substrings of the specified type in the specified range of the string.

Declaration

func enumerateSubstringsInRange(range: Range<Index>, options opts: NSStringEnumerationOptions, _ body: (substring: String?, substringRange: Range<Index>, enclosingRange: Range<Index>, inout Bool) -> ())
func getBytes(inout:maxLength:usedLength:encoding:options:range:remainingRange:)

[Foundation] Writes the given range of characters into buffer in a given encoding, without any allocations. Does not NULL-terminate.

buffer: A buffer into which to store the bytes from the receiver. The returned bytes are not NUL-terminated.

maxBufferCount: The maximum number of bytes to write to buffer.

usedBufferCount: The number of bytes used from buffer. Pass nil if you do not need this value.

encoding: The encoding to use for the returned bytes.

options: A mask to specify options to use for converting the receiver’s contents to encoding (if conversion

is necessary).

range: The range of characters in the receiver to get.

leftover: The remaining range. Pass nil If you do not need this value.

Returns: true iff some characters were converted.

Note: Conversion stops when the buffer fills or when the conversion isn't possible due to the chosen encoding.

Note: will get a maximum of min(buffer.count, maxLength) bytes.

Declaration

func getBytes(inout buffer: [UInt8], maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: NSStringEncoding, options: NSStringEncodingConversionOptions, range: Range<Index>, remainingRange leftover: UnsafeMutablePointer<Range<Index>>) -> Bool
func getCString(inout:maxLength:encoding:)

[Foundation] Converts the String’s content to a given encoding and

stores them in a buffer. Note: will store a maximum of min(buffer.count, maxLength) bytes.

Declaration

func getCString(inout buffer: [CChar], maxLength: Int, encoding: NSStringEncoding) -> Bool
func getLineStart(_:end:contentsEnd:forRange:)

[Foundation] Returns by reference the beginning of the first line and the end of the last line touched by the given range.

Declaration

func getLineStart(start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, forRange: Range<Index>)
func getParagraphStart(_:end:contentsEnd:forRange:)

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

Declaration

func getParagraphStart(start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, forRange: Range<Index>)
func hasPrefix(_:)

Returns true iff self begins with prefix.

Declaration

func hasPrefix(prefix: String) -> Bool
func hasSuffix(_:)

Returns true iff self ends with suffix.

Declaration

func hasSuffix(suffix: String) -> Bool
mutating func insert(_:atIndex:)

Insert newElement at index i.

Invalidates all indices with respect to self.

Complexity: O(self.count).

Declaration

mutating func insert(newElement: Character, atIndex i: Index)
mutating func insertContentsOf(_:at:)

Insert newElements at index i.

Invalidates all indices with respect to self.

Complexity: O(self.count + newElements.count).

Declaration

mutating func insertContentsOf<S : CollectionType where S.Generator.Element == Character>(newElements: S, at i: Index)
func lengthOfBytesUsingEncoding(_:)

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

Declaration

func lengthOfBytesUsingEncoding(encoding: NSStringEncoding) -> Int
func lineRangeForRange(_:)

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

Declaration

func lineRangeForRange(aRange: Range<Index>) -> Range<Index>
func linguisticTagsInRange(_:scheme:options:orthography:tokenRanges:)

[Foundation] Returns an array of linguistic tags for the specified range and requested tags within the receiving string.

Declaration

func linguisticTagsInRange(range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTaggerOptions = default, orthography: NSOrthography? = default, tokenRanges: UnsafeMutablePointer<[Range<Index>]> = default) -> [String]
func localizedCaseInsensitiveCompare(_:)

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

Declaration

func localizedCaseInsensitiveCompare(aString: String) -> NSComparisonResult
func localizedCaseInsensitiveContainsString(_:)

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

Locale-independent case-insensitive operation, and other needs, can be achieved by calling rangeOfString(_:options:,range:_locale:_).

Equivalent to

self.rangeOfString(
  other, options: .CaseInsensitiveSearch,
  locale: NSLocale.currentLocale()) != nil

Declaration

func localizedCaseInsensitiveContainsString(other: String) -> Bool
func localizedCompare(_:)

[Foundation] Compares the string and a given string using a localized comparison.

Declaration

func localizedCompare(aString: String) -> NSComparisonResult
func localizedStandardCompare(_:)

[Foundation] Compares strings as sorted by the Finder.

Declaration

func localizedStandardCompare(string: String) -> NSComparisonResult
func localizedStandardContainsString(_:)

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

This is the most appropriate method for doing user-level string searches, similar to how searches are done generally in the system. The search is locale-aware, case and diacritic insensitive. The exact list of search options applied may change over time.

Declaration

func localizedStandardContainsString(string: String) -> Bool
func localizedStandardRangeOfString(_:)

[Foundation] 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.

This is the most appropriate method for doing user-level string searches, similar to how searches are done generally in the system. The search is locale-aware, case and diacritic insensitive. The exact list of search options applied may change over time.

Declaration

func localizedStandardRangeOfString(string: String) -> Range<Index>?
func lowercaseStringWithLocale(_:)

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

Declaration

func lowercaseStringWithLocale(locale: NSLocale?) -> String
func maximumLengthOfBytesUsingEncoding(_:)

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

Declaration

func maximumLengthOfBytesUsingEncoding(encoding: NSStringEncoding) -> Int
func paragraphRangeForRange(_:)

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

Declaration

func paragraphRangeForRange(aRange: Range<Index>) -> Range<Index>
func propertyList()

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

Declaration

func propertyList() -> AnyObject
func propertyListFromStringsFileFormat()

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

Declaration

func propertyListFromStringsFileFormat() -> [String : String]
func rangeOfCharacterFromSet(_:options:range:)

[Foundation] 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.

Declaration

func rangeOfCharacterFromSet(aSet: NSCharacterSet, options mask: NSStringCompareOptions = default, range aRange: Range<Index>? = default) -> Range<Index>?
func rangeOfComposedCharacterSequenceAtIndex(_:)

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

Declaration

func rangeOfComposedCharacterSequenceAtIndex(anIndex: Index) -> Range<Index>
func rangeOfComposedCharacterSequencesForRange(_:)

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

Declaration

func rangeOfComposedCharacterSequencesForRange(range: Range<Index>) -> Range<Index>
func rangeOfString(_:options:range:locale:)

[Foundation] 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.

Declaration

func rangeOfString(aString: String, options mask: NSStringCompareOptions = default, range searchRange: Range<Index>? = default, locale: NSLocale? = default) -> Range<Index>?
mutating func removeAll(keepCapacity:)

Remove all characters.

Invalidates all indices with respect to self.

keepCapacity: If true, prevents the release of allocated storage, which can be a useful optimization when self is going to be grown again.

Declaration

mutating func removeAll(keepCapacity keepCapacity: Bool = default)
mutating func removeAtIndex(_:)

Remove and return the element at index i.

Invalidates all indices with respect to self.

Complexity: O(self.count).

Declaration

mutating func removeAtIndex(i: Index) -> Character
mutating func removeRange(_:)

Remove the indicated subRange of characters.

Invalidates all indices with respect to self.

Complexity: O(self.count).

Declaration

mutating func removeRange(subRange: Range<Index>)
mutating func replaceRange(_: Range<Index>, with: String)

Replace the given subRange of elements with newElements.

Invalidates all indices with respect to self.

Complexity: O(subRange.count) if subRange.endIndex == self.endIndex and newElements.isEmpty, O(N) otherwise.

Declaration

mutating func replaceRange(subRange: Range<Index>, with newElements: String)
mutating func replaceRange<C : CollectionType where C.Generator.Element == Character>(_: Range<Index>, with: C)

Replace the given subRange of elements with newElements.

Invalidates all indices with respect to self.

Complexity: O(subRange.count) if subRange.endIndex == self.endIndex and newElements.isEmpty, O(N) otherwise.

Declaration

mutating func replaceRange<C : CollectionType where C.Generator.Element == Character>(subRange: Range<Index>, with newElements: C)
mutating func reserveCapacity(_:)

Declaration

mutating func reserveCapacity(n: Int)
func stringByAddingPercentEncodingWithAllowedCharacters(_:)

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

Declaration

func stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters: NSCharacterSet) -> String?
func stringByAddingPercentEscapesUsingEncoding(_:)

[Foundation] 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: Use stringByAddingPercentEncodingWithAllowedCharacters(_:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid..

Declaration

func stringByAddingPercentEscapesUsingEncoding(encoding: NSStringEncoding) -> String?
func stringByAppendingFormat(_:_:)

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

Declaration

func stringByAppendingFormat(format: String, _ arguments: CVarArgType...) -> String
func stringByAppendingString(_:)

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

Declaration

func stringByAppendingString(aString: String) -> String
func stringByApplyingTransform(_:reverse:)

[Foundation] Perform string transliteration.

Declaration

func stringByApplyingTransform(transform: String, reverse: Bool) -> String?
func stringByFoldingWithOptions(_:locale:)

[Foundation] Returns a string with the given character folding options applied.

Declaration

func stringByFoldingWithOptions(options: NSStringCompareOptions, locale: NSLocale?) -> String
func stringByPaddingToLength(_:withString:startingAtIndex:)

[Foundation] 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.

Declaration

func stringByPaddingToLength(newLength: Int, withString padString: String, startingAtIndex padIndex: Int) -> String
func stringByReplacingCharactersInRange(_:withString:)

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

Declaration

func stringByReplacingCharactersInRange(range: Range<Index>, withString replacement: String) -> String
func stringByReplacingOccurrencesOfString(_:withString:options:range:)

[Foundation] 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.

Declaration

func stringByReplacingOccurrencesOfString(target: String, withString replacement: String, options: NSStringCompareOptions = default, range searchRange: Range<Index>? = default) -> String
func stringByReplacingPercentEscapesUsingEncoding(_:)

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

Deprecated: Use stringByRemovingPercentEncoding instead, which always uses the recommended UTF-8 encoding..

Declaration

func stringByReplacingPercentEscapesUsingEncoding(encoding: NSStringEncoding) -> String?
func stringByTrimmingCharactersInSet(_:)

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

Declaration

func stringByTrimmingCharactersInSet(set: NSCharacterSet) -> String
func substringFromIndex(_:)

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

Declaration

func substringFromIndex(index: Index) -> String
func substringToIndex(_:)

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

Declaration

func substringToIndex(index: Index) -> String
func substringWithRange(_:)

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

Declaration

func substringWithRange(aRange: Range<Index>) -> String
func uppercaseStringWithLocale(_:)

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

Declaration

func uppercaseStringWithLocale(locale: NSLocale?) -> String
func withCString(_:)

Invoke f on the contents of this string, represented as a nul-terminated array of char, ensuring that the array's lifetime extends through the execution of f.

Declaration

func withCString<Result>(@noescape f: UnsafePointer<Int8> throws -> Result) rethrows -> Result
mutating func withMutableCharacters(_:)

Efficiently mutate self by applying body to its characters.

Warning: Do not rely on anything about self (the String that is the target of this method) during the execution of body: it may not appear to have its correct value. Instead, use only the String.CharacterView argument to body.

Declaration

mutating func withMutableCharacters<R>(body: (inout String.CharacterView) -> R) -> R
mutating func write(_:)

Append other to this stream.

Declaration

mutating func write(other: String)
func writeTo(inout:)

Write a textual representation of self into target.

Declaration

func writeTo<Target : OutputStreamType>(inout target: Target)
func writeToFile(_:atomically:encoding:)

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

Declaration

func writeToFile(path: String, atomically useAuxiliaryFile: Bool, encoding enc: NSStringEncoding) throws
func writeToURL(_:atomically:encoding:)

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

Declaration

func writeToURL(url: NSURL, atomically useAuxiliaryFile: Bool, encoding enc: NSStringEncoding) throws