Skip to content

Commit 061512b

Browse files
committed
Impelment LossLessStringConvertible for UUID
1 parent 6577f3a commit 061512b

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

Sources/FoundationEssentials/UUID.swift

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ public typealias uuid_string_t = (Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8
1616

1717
/// Represents UUID strings, which can be used to uniquely identify types, interfaces, and other items.
1818
@available(macOS 10.8, iOS 6.0, tvOS 9.0, watchOS 2.0, *)
19-
public struct UUID : Hashable, Equatable, CustomStringConvertible, Sendable {
19+
public struct UUID : Hashable, Equatable, CustomStringConvertible, Sendable, LosslessStringConvertible {
2020
public private(set) var uuid: uuid_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
2121

2222
/* Create a new UUID with RFC 4122 version 4 random bytes */
@@ -57,6 +57,11 @@ public struct UUID : Hashable, Equatable, CustomStringConvertible, Sendable {
5757
public init(uuid: uuid_t) {
5858
self.uuid = uuid
5959
}
60+
61+
/// LosslessStringConvertible initializer
62+
public init?(_ description: String) {
63+
self.init(uuidString: description)
64+
}
6065

6166
/// Returns a string created from the UUID, such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
6267
public var uuidString: String {

Tests/FoundationEssentialsTests/UUIDTests.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,4 +115,19 @@ final class UUIDTests : XCTestCase {
115115
XCTAssertFalse(uuid2 > uuid1)
116116
XCTAssertTrue(uuid2 == uuid1)
117117
}
118+
119+
func test_UUIDLosslessStringConvertible() {
120+
let originalString = "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
121+
let uuidFromString = UUID(originalString)
122+
XCTAssertNotNil(uuidFromString, "UUID must be constructible from valid UUID string via LosslessStringConvertible")
123+
XCTAssertEqual(uuidFromString?.description, originalString, "Round-tripped description must match original UUID string")
124+
125+
let uuid = UUID(uuidString: originalString)!
126+
XCTAssertEqual(uuid, UUID(uuid.description), "UUID must round-trip through LosslessStringConvertible")
127+
128+
let invalidString = "not-a-uuid"
129+
let invalidUUID = UUID(invalidString)
130+
XCTAssertNil(invalidUUID, "Invalid UUID strings must result in nil from LosslessStringConvertible initializer")
131+
}
132+
118133
}

0 commit comments

Comments
 (0)