๐ŸŽ“ A1Learner
๐Ÿ”

Swift String Methods

A string method is a built-in action that a string can perform. A string method reads the string or builds a changed copy from it.

Counting characters with .count

A dot joins the string to the count value. The count of a known word gives a number that is easy to check.

let word = "banana"
print(word.count)

Capital and small copies

A dot joins the string and the method name at each call. The last print shows the stored spelling after both case calls.

let word = "Swift"
print(word.uppercased())
print(word.lowercased())
print(word)

Starts and ends

hasPrefix and hasSuffix each give true or false. The given piece must match the edge of the string.

print("notebook".hasPrefix("note"))
print("notebook".hasSuffix("pen"))

Finding text inside

contains gives true when the piece sits anywhere in the string. It gives false when the piece is absent.

print("pineapple".contains("apple"))
print("pineapple".contains("grape"))

Example

let title = "Swift Guide"
print(title.count)
print(title.lowercased())
print(title.hasPrefix("Swift"))
print(title.contains("Guide"))

Key points

  • .count: the number of characters in a string.
  • uppercased(): a copy of the string with every letter capital.
  • lowercased(): a copy of the string with every letter small.
  • hasPrefix checks whether a string starts with a given piece of text.
  • hasSuffix checks whether a string ends with a given piece of text.
  • contains checks whether a string holds a given piece of text.

In this example, title holds the string Swift Guide. The count print shows 11 characters. The lowercased print shows swift guide. The hasPrefix print shows true because the string starts with Swift. The contains print shows true because Guide sits inside the string.

Note

uppercased() and lowercased() build new strings and leave the stored string unchanged.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Swift Compiler

Exercise

A program sets word to "hello" and prints word.count. What prints?