find the extension of a file in swift

In Swift, you can find the file extension of a file by using the pathExtension property of the URL class. Here's an example:

main.swift
let fileURL = URL(fileURLWithPath: "/path/to/file.txt")
let fileExtension = fileURL.pathExtension
print(fileExtension) // "txt"
128 chars
4 lines

In the code above, we create a URL object with the path to our file. We then access the pathExtension property of the URL object to get the file extension.

Note that the pathExtension property only returns the extension of the file name, not including the period (.) separator. If you need to include the period separator, you can manually append it to the extension string:

main.swift
let fileExtensionWithPeriod = "." + fileURL.pathExtension
print(fileExtensionWithPeriod) // ".txt"
99 chars
3 lines

gistlibby LogSnag