Library reference

Match the end of a string

Check the letters at the end of the text. The result is true only when those letters match.

String.hasSuffix

Simple example

Does abc end with c?

Start'abc' · 'c'
Resulttrue
main.swift
import Foundation

print("abc".hasSuffix("c"))
Output
true
Advertisements

Everyday examples

A teacher wants PDF files. Does this name end in .pdf?

Start'notes.pdf' · '.pdf'
Resulttrue
main.swift
import Foundation

print("notes.pdf".hasSuffix(".pdf"))
Output
true

A music player lists MP3 files. Does the recording have that ending?

Start'rehearsal.wav' · '.mp3'
Resultfalse
main.swift
import Foundation

print("rehearsal.wav".hasSuffix(".mp3"))
Output
false

Fragile shelf labels end in -F. Does this one belong there?

Start'12-F' · '-F'
Resulttrue
main.swift
import Foundation

print("12-F".hasSuffix("-F"))
Output
true
Run the example
Terminal
swift main.swift
Official documentation