There are different ways of representing a type of file, two popular ones being file extensions and another being Uniform Type Identifiers (UTIs) from the UIKit APIs. When working with a UIKit API such as UIDocumentPickerViewController
we may need to distinguish between these types.
We can create independent types to hold file extensions and type identifiers, this makes it really clear which one is required for a particular piece of functionality.
struct FileExtension {
let rawValue: String
func asTypeIdentifier() -> TypeIdentifier {
let identifierCreated = UTTypeCreatePreferredIdentifierForTag(
kUTTagClassFilenameExtension, rawValue as NSString, nil
)
if let typeIdentifier = identifierCreated?.takeRetainedValue() {
return TypeIdentifier(rawValue: typeIdentifier as String)
}
return TypeIdentifier(rawValue: "public.data")
}
}
struct TypeIdentifier {
let rawValue: String
}
I hope the article was useful. If you have any feedback or questions please feel free to reach out.
Thanks for reading!
WRITTEN BY
Andrew Lord
A software developer and tech leader from the UK. Writing articles that focus on all aspects of Android and iOS development using Kotlin and Swift.
Want to read more?
Here are some other articles you may enjoy.