Skip to content

Swift String API

Swift's String — a value type representing a sequence of Unicode scalar values (extended grapheme clusters).

1 class · 8 methods

String

8 methods

A Unicode string value that is a collection of characters. A value type bridged to NSString.

String.count -> Int

The number of characters (extended grapheme clusters) in the string.

Returns

Int

Example

swift
let s = "Hello"
print(s.count)  // 5

let cafe = "café"
print(cafe.count)  // 4
String.uppercased() -> String

Returns a new string made by replacing lowercase characters with uppercase ones.

Returns

String

Example

swift
let s = "Hello World"
print(s.uppercased())  // "HELLO WORLD"
String.lowercased() -> String

Returns a new string made by replacing uppercase characters with lowercase ones.

Returns

String

Example

swift
let s = "Hello World"
print(s.lowercased())  // "hello world"
String.hasPrefix(_ prefix: String) -> Bool

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

Parameters

NameTypeDescription
prefixStringPrefix to test for.

Returns

Bool

Example

swift
let s = "Hello, World"
print(s.hasPrefix("Hello"))  // true
print(s.hasPrefix("World"))  // false
String.hasSuffix(_ suffix: String) -> Bool

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

Parameters

NameTypeDescription
suffixStringSuffix to test for.

Returns

Bool

Example

swift
let s = "Hello, World"
print(s.hasSuffix("World"))  // true
print(s.hasSuffix("Hello"))  // false
String.contains(_ other: String) -> Bool

Returns true if the string contains the given string or character.

Parameters

NameTypeDescription
otherStringSubstring to search for.

Returns

Bool

Example

swift
let s = "Hello, World"
print(s.contains("World"))  // true
print(s.contains("xyz"))    // false
String.split(separator: Character) -> [Substring]

Returns the longest possible subsequences of the string, in order, around the separator.

Parameters

NameTypeDescription
separatorCharacterCharacter to split on.

Returns

[Substring]

Example

swift
let s = "a,b,c"
let parts = s.split(separator: ",")
// parts == ["a", "b", "c"]
String.replacingOccurrences(of: String, with: String) -> String

Returns a new string in which all occurrences of a target string are replaced by another.

Parameters

NameTypeDescription
ofStringString to replace.
withStringReplacement string.

Returns

String

Example

swift
let s = "Hello, World"
let r = s.replacingOccurrences(of: "World", with: "Swift")
// r == "Hello, Swift"