Skip to content

Commit

Permalink
add nomatchingformat enum
Browse files Browse the repository at this point in the history
  • Loading branch information
dlo committed Nov 9, 2024
1 parent 93dc8f1 commit 61c0f14
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions Sources/Core/DateFormatter+LionheartExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,16 @@

import Foundation

public struct NoMatchingFormat {
public var input: String
public var format: String
}

public enum DateFormatError: Error {
case emptyDates
case inconsistentFormat
case unspecified
case noMatchingFormat
case noMatchingFormat(NoMatchingFormat?)
}

fileprivate struct DateFormatterString {
Expand Down Expand Up @@ -84,7 +89,7 @@ public extension DateFormatter {
formatters.append(DateFormatter(format: DateFormatterString.DateComponent6))

case 3: timeFormatStrings = DateFormatterString.ThreeSpaceFormatStrings
default: throw DateFormatError.noMatchingFormat
default: throw DateFormatError.noMatchingFormat(nil)
}

for dateString in DateFormatterString.NoSpaceFormatStrings {
Expand All @@ -97,19 +102,27 @@ public extension DateFormatter {
}
}

var noMatchingFormat: NoMatchingFormat? = nil
formatterLoop: for formatter in formatters {
var i = 0
for dateString in dateStrings {
guard formatter.date(from: dateString) != nil else {
// Skip to the next formatter if a string failed to parse with this formatter.
if i > (dateStrings.count / 2) {
noMatchingFormat = NoMatchingFormat(input: dateString, format: formatter.dateFormat)
}

continue formatterLoop
}

i += 1
}

// If we got here, all of the strings worked with this formatter.
return formatter
}

// No date formatter worked for everything. Fail.
throw DateFormatError.noMatchingFormat
throw DateFormatError.noMatchingFormat(noMatchingFormat)
}
}

0 comments on commit 61c0f14

Please sign in to comment.