Skip to content

Conform LossLessStringConvertible for UUID #1303

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion Sources/FoundationEssentials/UUID.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public struct UUID : Hashable, Equatable, CustomStringConvertible, Sendable {
public init(uuid: uuid_t) {
self.uuid = uuid
}

/// Returns a string created from the UUID, such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
public var uuidString: String {
var bytes: uuid_string_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
Expand Down Expand Up @@ -150,3 +150,11 @@ extension UUID : Comparable {
return result < 0
}
}

@available(FoundationPreview 6.2, *)
extension UUID: LosslessStringConvertible {
/// Create a UUID from a string representation conforming to `LosslessStringConvertible`.
public init?(_ description: String) {
self.init(uuidString: description)
}
}
15 changes: 15 additions & 0 deletions Tests/FoundationEssentialsTests/UUIDTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,19 @@ final class UUIDTests : XCTestCase {
XCTAssertFalse(uuid2 > uuid1)
XCTAssertTrue(uuid2 == uuid1)
}

func test_UUIDLosslessStringConvertible() {
let originalString = "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
let uuidFromString = UUID(originalString)
XCTAssertNotNil(uuidFromString, "UUID must be constructible from valid UUID string via LosslessStringConvertible")
XCTAssertEqual(uuidFromString?.description, originalString, "Round-tripped description must match original UUID string")

let uuid = UUID(uuidString: originalString)!
XCTAssertEqual(uuid, UUID(uuid.description), "UUID must round-trip through LosslessStringConvertible")

let invalidString = "not-a-uuid"
let invalidUUID = UUID(invalidString)
XCTAssertNil(invalidUUID, "Invalid UUID strings must result in nil from LosslessStringConvertible initializer")
}

}