Last active
October 9, 2023 15:38
-
-
Save hisavali/d9e7f7ede1af60604be80f7c619773de to your computer and use it in GitHub Desktop.
Parse: Use-case based on swift-parsing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import XCTest | |
import Parsing // https://github.com/pointfreeco/swift-parsing | |
struct ParsedData { | |
let key1: Int | |
let key2: UUID? | |
let key3: String | |
} | |
let parser = Parse(input: Substring.self) { | |
/* first line */ | |
"Key1: " | |
Int.parser() | |
Whitespace(1, .vertical) | |
/* second line */ | |
Optionally { | |
"Key2: " | |
Optionally { | |
UUID.parser() | |
} | |
Whitespace(1, .vertical) | |
} | |
/* third line */ | |
"Key3: " | |
Prefix { $0 != "\n" }.map(.string) | |
} | |
let inputVariant1 = """ | |
Key1: 100 | |
Key2: AF4D13D7-26C8-41E2-9CB8-AC03CE827921 | |
Key3: iphone | |
""" | |
let inputVariant2 = """ | |
Key1: 100 | |
Key2: | |
Key3: iphone | |
""" | |
let inputVariant3 = """ | |
Key1: 100 | |
Key3: iphone | |
""" | |
final class Experiment: XCTestCase { | |
func testExample() throws { | |
do { | |
let parsedVariant1 = try parser.parse(inputVariant1) //✅ | |
print(parsedVariant1) | |
let parsedVariant2 = try parser.parse(inputVariant2) //❌ | |
print(parsedVariant2) | |
let parsedVariant3 = try parser.parse(inputVariant3) //✅ | |
print(parsedVariant3) | |
} catch { | |
print(error) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment