Nothing is ever 100% safe in programming, especially when dealing with an SDK where the implementation is hidden. I answered a similar question about the constant NSNotFound
here.
Is NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
safe? Ideally, if Apple choses not to change their SDK, or if they provide a bug-free implementation of the NSCalendar
initializer. As far as defensive coding goes, you have two options.
Wrap the code in a guard
as Leo Dabus suggested in the comments:
guard let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) else { return }
For future-proofing, Apple may change the availability or implementation of the
NSCalendarIdentifier
constants (as seen with NSNotFound
). For added safety, check the memory location of the constant:
if let str: String = NSCalendarIdentifierGregorian {
if let _: UnsafePointer<Void> = unsafeAddressOf(str) {
// NSCalendarIdentifierGregorian is defined on your platform
}
}
It's a little bit cleaner in Objective-C:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-compare"
BOOL found = (&NSCalendarIdentifierGregorian != NULL);
#pragma clang diagnostic pop
if (found) {
// safe
}
I do not work for Apple and cannot guarantee the availability of any Foundation classes.