0

I am trying to determine if the swift Calendar struct is thread safe. I found that the NSCalendar class is "generally considered to be thread safe". But I can not find specific information for the Calendar struct.

My goal is to extend the Date struct with a Calendar for use with extension methods such as yesterday, tomorrow, etc. I don't want to create a new Calendar instance with each call.

3Stone
  • 143
  • 6
  • `extension Calendar { static let iso8601 = Calendar(identifier: .iso8601) }` – Leo Dabus Aug 29 '17 at 21:45
  • and just use `Calendar.iso8601.whatever` https://stackoverflow.com/a/45242626/2303865 – Leo Dabus Aug 29 '17 at 21:46
  • To Leo's point, that works, but depending upon what sorts of functions you are using, it might be more prudent to use `Calendar.current`. ISO 8601 is fine for dates in web services or databases, but for anything you're showing to the end user, `Calendar.current` would be better. – Rob Aug 30 '17 at 00:08
  • Thanks, currently, for my app, I'm only supporting Gregorian. – 3Stone Aug 30 '17 at 20:08

3 Answers3

0

Calendar is meant to be a drop-in replacement for NSCalendar, and in fact is just a wrapper around NSCalendar on Apple platforms, so if NSCalendar is thread-safe, I'd expect that Calendar is as well.

Charles Srstka
  • 16,665
  • 3
  • 34
  • 60
0

If you looked at Calendar's source code, you won't see any code to make it thread safe. So I think it's not, and different threads will see different versions of the Calendar's object fields.

Mo Abdul-Hameed
  • 6,030
  • 2
  • 23
  • 36
0

No, it's not thread-safe (at least when running on Linux). Not sure if Darwin implementation is different. https://bugs.swift.org/browse/SR-11323

If anybody is curious the implementation is here: https://github.com/apple/swift-corelibs-foundation/blob/master/CoreFoundation/Locale.subproj/CFCalendar.c

There are lots of places where "calendar->_cal" (which is shared between concurrent invocations) is modified and used as a temporary storage.