From 6f30a97fb8aa28c60fec6507c6bee0b8cfdf000e Mon Sep 17 00:00:00 2001 From: cosmer-work <50632918+cosmer-work@users.noreply.github.com> Date: Tue, 16 May 2023 16:58:27 -0400 Subject: [PATCH] Fix ambiguous phone number detection (#642) `possibleResults` could end up with multiple instances of identical phone numbers leading to an incorrect `ambiguousNumber` error. --- PhoneNumberKit/Constants.swift | 2 +- PhoneNumberKit/ParseManager.swift | 6 +++--- PhoneNumberKitTests/PhoneNumberKitParsingTests.swift | 6 ++++++ 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/PhoneNumberKit/Constants.swift b/PhoneNumberKit/Constants.swift index 413922130..d8a160a19 100644 --- a/PhoneNumberKit/Constants.swift +++ b/PhoneNumberKit/Constants.swift @@ -40,7 +40,7 @@ public enum PhoneNumberError: Error, Equatable { case tooShort case deprecated case metadataNotFound - case ambiguousNumber(phoneNumbers: [PhoneNumber]) + case ambiguousNumber(phoneNumbers: Set) } extension PhoneNumberError: LocalizedError { diff --git a/PhoneNumberKit/ParseManager.swift b/PhoneNumberKit/ParseManager.swift index c576117f4..5859891b5 100644 --- a/PhoneNumberKit/ParseManager.swift +++ b/PhoneNumberKit/ParseManager.swift @@ -75,18 +75,18 @@ final class ParseManager { } // If everything fails, iterate through other territories with the same country code (7) - var possibleResults = [PhoneNumber]() + var possibleResults: Set = [] if let metadataList = metadataManager.filterTerritories(byCode: countryCode) { for metadata in metadataList where regionMetadata.codeID != metadata.codeID { if let result = try validPhoneNumber(from: nationalNumber, using: metadata, countryCode: countryCode, ignoreType: ignoreType, numberString: numberString, numberExtension: numberExtension) { - possibleResults.append(result) + possibleResults.insert(result) } } } switch possibleResults.count { case 0: throw PhoneNumberError.notANumber - case 1: return possibleResults[0] + case 1: return possibleResults.first! default: throw PhoneNumberError.ambiguousNumber(phoneNumbers: possibleResults) } } diff --git a/PhoneNumberKitTests/PhoneNumberKitParsingTests.swift b/PhoneNumberKitTests/PhoneNumberKitParsingTests.swift index dc75a7481..c244e2457 100644 --- a/PhoneNumberKitTests/PhoneNumberKitParsingTests.swift +++ b/PhoneNumberKitTests/PhoneNumberKitParsingTests.swift @@ -547,4 +547,10 @@ class PhoneNumberKitParsingTests: XCTestCase { XCTAssertEqual(number.type, PhoneNumberType.mobile) XCTAssertEqual(number.numberExtension, "22") } + + func testNonAmbiguousPhoneNumber() { + // This phone number was incorrectly identified as ambiguous. + let address = "+1 345 916 1234" + try XCTAssertNotNil(phoneNumberKit.parse(address, withRegion: "JM")) + } }