Swift - get file extension

Aus Wikizone
Wechseln zu: Navigation, Suche

Links[Bearbeiten]

Swift - Snippets

Beispiele[Bearbeiten]

To get the file extension of a filename in Swift, you can use the pathExtension property of the URL struct. For example:

let fileURL = URL(fileURLWithPath: "path/to/file.txt")
let fileExtension = fileURL.pathExtension
print(fileExtension)  // prints "txt"

Alternatively, you can use the NSURL class from the Foundation framework, which has a similar pathExtension property:

let fileURL = NSURL(fileURLWithPath: "path/to/file.txt")
let fileExtension = fileURL.pathExtension
print(fileExtension)  // prints "txt"

Both of these approaches work by parsing the file path as a URL and extracting the part of the path after the last period (.) character. This assumes that the file extension is the portion of the filename after the last period, which is the convention for most file formats.

If you want to handle cases where the file name does not have a period or where the file extension is not the portion of the filename after the last period, you can use string manipulation functions such as split(separator:), components(separatedBy:), or range(of:) to extract the file extension manually.