diff --git a/Sources/KituraContracts/Contracts.swift b/Sources/KituraContracts/Contracts.swift index 6618807..fd0b12d 100644 --- a/Sources/KituraContracts/Contracts.swift +++ b/Sources/KituraContracts/Contracts.swift @@ -963,6 +963,23 @@ extension Bool: Identifier { } } +extension UUID: Identifier { + /// Creates a UUID identifier from a given string representation. + /// - Throws: An `IdentifierError.invalidValue` if the given string cannot be converted to a UUID. + public init(value: String) throws { + if let id = UUID(uuidString: value) { + self = id + } else { + throw IdentifierError.invalidValue + } + } + + /// The string representation of the identifier. + public var value: String { + return self.uuidString + } +} + /** An enum containing the ordering information ### Usage Example: ### diff --git a/Tests/KituraContractsTests/KituraContractsTests.swift b/Tests/KituraContractsTests/KituraContractsTests.swift index 80e54fa..29f2854 100644 --- a/Tests/KituraContractsTests/KituraContractsTests.swift +++ b/Tests/KituraContractsTests/KituraContractsTests.swift @@ -72,6 +72,25 @@ class KituraContractsTests: XCTestCase { XCTAssertEqual(123456, intIdentifier) } + // Test UUID conforms to Identifier + func testUUIDIdentifier() { + let uuidStr = "12345678-1234-4000-ABCD-BA9876543210" + guard let identifier: Identifier = try? UUID(value: uuidStr) else { + XCTFail("Failed to create a UUID identifier!") + return + } + XCTAssertEqual(uuidStr, identifier.value) + + guard let uuidIdentifier = identifier as? UUID else { + XCTFail("Failed to cast to concrete type: UUID") + return + } + XCTAssertEqual(UUID(uuidString: uuidStr), uuidIdentifier) + + let bogusUUIDStr = "NOPE" + XCTAssertThrowsError(try UUID(value: bogusUUIDStr), "Failed to throw with bogus UUID value") + } + // func testTypeComputation() { // XCTAssertEqual(User.type, "User") // XCTAssertEqual(User.typeLowerCased, "user")