From 1a384d876244e546e561ea37b5aba4957205f8b8 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Sun, 24 Nov 2024 01:06:25 -0500 Subject: [PATCH] Add `LosslessStringConvertible` conformance to `BluetoothAddress` --- Sources/Bluetooth/Address.swift | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/Sources/Bluetooth/Address.swift b/Sources/Bluetooth/Address.swift index 9a8eacec9..3d8e8c633 100644 --- a/Sources/Bluetooth/Address.swift +++ b/Sources/Bluetooth/Address.swift @@ -88,7 +88,7 @@ extension BluetoothAddress: RawRepresentable { } /// Initialize a Bluetooth Address from its big endian string representation (e.g. `00:1A:7D:DA:71:13`). - internal init?(_ rawValue: S) { + internal static func parse(_ rawValue: S) -> Self? { // verify string length let characters = rawValue.utf8 @@ -116,7 +116,7 @@ extension BluetoothAddress: RawRepresentable { } } - self.init(bigEndian: BluetoothAddress(bytes: bytes)) + return BluetoothAddress(bigEndian: BluetoothAddress(bytes: bytes)) } /// Convert a Bluetooth Address to its big endian string representation (e.g. `00:1A:7D:DA:71:13`). @@ -138,6 +138,18 @@ extension BluetoothAddress: CustomStringConvertible { public var description: String { rawValue } } +// MARK: - LosslessStringConvertible + +extension BluetoothAddress: LosslessStringConvertible { + + public init?(_ string: String) { + guard let value = BluetoothAddress.parse(string) else { + return nil + } + self = value + } +} + // MARK: - Data extension BluetoothAddress: DataConvertible {