MediaType is a library that can be used to create Media Types in a type-safe manner.

Overview

MediaType

Overview

MediaType is a library that can be used to create Media Types in a type-safe manner.

Mainly intended – although not limited – to be used in server-side Swift applications.

Creating Media Types

Media types are represented by the MediaType Swift type.

You can create a media type in a type-safe manner using one of the possible cases. You can also create media type instances simply by using string literals.

let mediaType: MediaType = "application/json" // is equivalent to
MediaType.application(.json())

It is also possible to create a MediaType instance from a string variable as shown in the following example.

let rawMediaType = "application/json"
let mediaType = MediaType(rawValue: rawMediaType)

Suffixes and Parameters

Media type Suffixes and Parameters are supported both via string literals and MediaType cases.

let mediaType: MediaType = "application/atom; charset=utf-8" // is equivalent to
MediaType.application(.atom(nil, ["charset": "utf-8"]))

let mediaType: MediaType = "application/atom+xml" // is equivalent to
MediaType.application(.atom(.xml))

let mediaType: MediaType = "application/atom+xml; charset=utf-8" // is equivalent to
MediaType.application(.atom(.xml, ["charset": "utf-8"]))

Trees

You can create media type trees by using either the string literal syntax, or using the other case of a particular media type.

let mediaType: MediaType = "application/vnd.efi.img" // is equivalent to
MediaType.application(.other("vnd.efi.img"))

Unregistered Media Types

Using this library you can create all the registered media types. The library is versatile enough to allow you to create practically any media type, even ones that are not registered. A few examples of such cases:

let image: MediaType = "image/svg+gzip" // is equivalent to
MediaType.image(.svg(.gzip))

let application: MediaType = "application/myApp+json" // is equivalent to
MediaType.application(.other("myApp", .json))

Using Media Types

You can use regular switch statements to test for media types and get access to their components. The following example shows various ways to treat a media type.

func isSupported(_ mediaType: MediaType) -> Bool {
  switch mediaType {
  case .application(.json(_, _)): return true
  case .application(.atom("xml", _)): return true
  case .application(let subtype):
    switch subtype {
    case .xml(_, _): return true
    default: return false
    }
  default: return false
  }
}

isSupported("application/json") // Returns: true
isSupported("application/json+xml") // Returns: true
isSupported("application/json;charset=utf-8") // Returns: true
isSupported("application/json+xml;charset=utf-8") // Returns: true

isSupported("application/atom+xml") // Returns: true
isSupported("application/atom+xml;charset=utf-8") // Returns: true
isSupported("application/atom") // Returns: false
isSupported("application/atom;charset=utf-8") // Returns: false

String Conversion

Since MediaType conforms to the CustomStringConvertible protocol it is pretty straightforward to turn an instance into a string.

You can either call the MediaType/description computed property or simply embed an instance into an interpolated string.

For example, you can request the list of available products in JSON from an imaginary store.

var request = URLRequest(url: URL(string: "https://example-store.com/products")!)
let contentType: MediaType = "application/json"

// The following two statements are equivalent
request.setValue("Content-Type", forHTTPHeaderField: "\(contentType)")
request.setValue("Content-Type", forHTTPHeaderField: contentType.description)

let (_, response) = try await URLSession.shared.data(for: request)

Media Types are Hashable

This means you can use MediaTypes in sets or dictionaries. For example, you can define the type of images your application supports like so:

let supportedImages: Set = ["image/png", "image/gif", "image/jpeg"]

Comparing Media Types

You can also compare media type for equality using the MediaType/==(lhs:rhs:) operator.

func canHandle(response: URLResponse) -> Bool {
  guard let mimeType = response.mimeType else { return false }
  let mediaType = MediaType(rawValue: mimeType)
  return mediaType == .application(.json())
}
You might also like...
Numerals is a package containing additional numeric types for the Swift programming language.

swift-numerals Numerals is a package containing additional numeric types for the Swift programming language. Contents The package currently provides t

Swift package adding fraction and percentage types.

swift-rationals Rationals is a package containing Fraction and Percentage types for the Swift programming language. Contents The package currently pro

Swift package adding measurable types.

swift-measures Measures is a package containing measurable types for the Swift programming language. Contents The package currently provides the follo

Parsing indeterminate types with Decodable and Either enum using Swift

Decodable + Either Parsing indeterminate types with Decodable and Either enum us

Extensions for Swift Standard Types and Classes

Cent Cent is a library that extends certain Swift object types using the extension feature and gives its two cents to Swift language. Dollar is a Swif

Unboxing - An extension for KeyedDecodingContainer class to decode a collection of heterogeneous types.

Unboxing An extension for KeyedDecodingContainer class to decode a collection of heterogeneous types. Usage Start by creating an enum that has variant

A reverse engineering tool to restore stripped symbol table and dump Objective-C class or Swift types for machO file.

A reverse engineering tool to restore stripped symbol table and dump Objective-C class or Swift types for machO file.

A lightweight extension to Swift's CollectionDifference, supporting moves in addition to removals and insertions, critical when updating interfaces and managing reference types.

DifferenceTracker is a lightweight extension to Swift's CollectionDifference. It defines moves in addition to removals and insertions, critical when updating interfaces and managing reference types.

A collection of useful result builders for Swift and Foundation value types

Swift Builders A collection of useful result builders for Swift and Foundation value types. Motivation Arrays, dictionaries, and other collection-base

Owner
21Gram Consulting
Pragmatic & result-oriented group of Digital Business Development professionals. Move fast, win more.
21Gram Consulting
Protected is a Swift Package that allows you to specify the read and write rights for any type, depending on context by using Phantom types

Protected is a Swift Package that allows you to specify the read and write rights for any type, depending on context by using Phantom types

Mathias Quintero 9 Sep 25, 2022
🚀Comprehensive Redux library for SwiftUI, ensures State consistency across Stores with type-safe pub/sub pattern.

??Comprehensive Redux library for SwiftUI, ensures State consistency across Stores with type-safe pub/sub pattern.

Cheng Zhang 18 Mar 9, 2022
Type-Safe Associated Objects in Swift

Type-Safe Associated Objects in Swift TSAO is an implementation of type-safe associated objects in Swift. Objective-C associated objects are useful, b

Lily Ballard 135 Dec 21, 2022
A simple macOS utility that can be used to control the behaviour of Bose QC35 Headphones straight from the menu bar.

bose-macos-utility A simple macOS utility that can be used to control the behaviour of Bose QC35 Headphones straight from the menu bar. Why Have you e

Łukasz Zalewski 11 Aug 26, 2022
A NEWS app which can be used to read,share and bookmark articles of various categories

Scoop A NEWS App for iOS 14 built using Swift which allow the users to read,bookmark and share news articles. Built using MVC architecture Requirement

Sai Balaji 3 Oct 12, 2022
A Swift μ-Library for Somewhat Dependent Types

Validated Validated is a μ-library (~50 Source Lines of Code) that allows you make better use of Swift's type system by providing tools for easily gen

Benjamin Encz 608 Oct 28, 2022
How Swift standard types and classes were supposed to work.

How Swift standard types and classes were supposed to work. A collection of useful extensions for the Swift Standard Library, Foundation, and UIKit.

Goktug Yilmaz 3k Dec 22, 2022
Functional data types and functions for any project

Swiftx Swiftx is a Swift library containing functional abstractions and extensions to the Swift Standard Library. Swiftx is a smaller and simpler way

TypeLift 219 Aug 30, 2022
The ISO 8601 period/duration types missing in Foundation

PeriodDuration This library introduces a close equivalent to Java's PeriodDuration, motivated by the lack of support for this standard in Foundation.

David Roman 19 Jun 22, 2022