Skip to content

Instantly share code, notes, and snippets.

@scott-lydon
Created June 25, 2021 01:28
Show Gist options
  • Save scott-lydon/b61b15e78c373b166570a872728cae46 to your computer and use it in GitHub Desktop.
Save scott-lydon/b61b15e78c373b166570a872728cae46 to your computer and use it in GitHub Desktop.
A playground demo to demonstrate a common race condition
import UIKit
public extension DateFormatter {
static let iso8601withFractionalSeconds: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return formatter
}()
}
let naive = DateFormatter.iso8601withFractionalSeconds
print("-naive: yay!, I can access the iso8601withFractionalSeconds and trust that it will be: ", naive, " unless I change it in the scope that I am in of course!")
extension DateFormatter {
static var yyyyMMDDFormat: DateFormatter {
let new = DateFormatter.iso8601withFractionalSeconds
new.dateFormat = "yyyy-MM-dd"
return new
}
}
let newFormatter = DateFormatter.yyyyMMDDFormat
print("-other naive: cool I've got a Dateformatter that I can trust with the yyyy-MM-dd format: ", newFormatter)
print("-naive: wth! when I display the date, it should be using \("yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX") but its actually using: yyyy-MM-dd", naive)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment