Added example to pattern match on a media type to README.
This commit is contained in:
parent
32fa18eced
commit
a395dcbfe2
28
README.md
28
README.md
|
@ -64,6 +64,34 @@ MediaType.application(.other("myApp", .json)) // Creates: application/myApp+json
|
|||
|
||||
## Using Media Types
|
||||
|
||||
You can use regular `swift` statements to test for media types and get access to their components. The following example
|
||||
shows various ways to treat a media type.
|
||||
|
||||
```swift
|
||||
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
|
||||
|
|
|
@ -55,4 +55,29 @@ extension CodeExamples {
|
|||
XCTAssertEqual(MediaType.image(.svg(.gzip)), "image/svg+gzip")
|
||||
XCTAssertEqual(MediaType.application(.other("myApp", .json)), "application/myApp+json")
|
||||
}
|
||||
|
||||
func test_matching() {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
XCTAssertTrue(isSupported("application/json"))
|
||||
XCTAssertTrue(isSupported("application/json+xml"))
|
||||
XCTAssertTrue(isSupported("application/json;charset=utf-8"))
|
||||
XCTAssertTrue(isSupported("application/json+xml;charset=utf-8"))
|
||||
|
||||
XCTAssertTrue(isSupported("application/atom+xml"))
|
||||
XCTAssertTrue(isSupported("application/atom+xml;charset=utf-8"))
|
||||
XCTAssertFalse(isSupported("application/atom"))
|
||||
XCTAssertFalse(isSupported("application/atom;charset=utf-8"))
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue