Skip to content

Commit 699d2c9

Browse files
authored
Merge pull request swiftlang#1142 from bubski/timezone-init
2 parents a8d9370 + 6545d1b commit 699d2c9

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

Foundation/TimeZone.swift

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,12 +80,15 @@ public struct TimeZone : Hashable, Equatable, ReferenceConvertible {
8080
/// - parameter seconds: The number of seconds from GMT.
8181
/// - returns: A time zone, or `nil` if a valid time zone could not be created from `seconds`.
8282
public init?(secondsFromGMT seconds: Int) {
83-
if let r = NSTimeZone(forSecondsFromGMT: seconds) as NSTimeZone? {
84-
_wrapped = r
85-
_autoupdating = false
86-
} else {
87-
return nil
88-
}
83+
// Seconds boundaries check should actually be placed in NSTimeZone.init(forSecondsFromGMT:) which should return
84+
// nil if the check fails. However, NSTimeZone.init(forSecondsFromGMT:) is not a failable initializer, so it
85+
// cannot return nil.
86+
// It is not a failable initializer because we want to have parity with Darwin's NSTimeZone, which is
87+
// Objective-C and has a wrong _Nonnull annotation.
88+
if (seconds < -18 * 3600 || 18 * 3600 < seconds) { return nil }
89+
90+
_wrapped = NSTimeZone(forSecondsFromGMT: seconds)
91+
_autoupdating = false
8992
}
9093

9194
/// Returns a time zone identified by a given abbreviation.

TestFoundation/TestNSTimeZone.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,12 @@ class TestNSTimeZone: XCTestCase {
153153

154154
let tz3 = TimeZone(identifier: "GMT-9999")
155155
XCTAssertNil(tz3)
156+
157+
XCTAssertNotNil(TimeZone(secondsFromGMT: -18 * 3600))
158+
XCTAssertNotNil(TimeZone(secondsFromGMT: 18 * 3600))
159+
160+
XCTAssertNil(TimeZone(secondsFromGMT: -18 * 3600 - 1))
161+
XCTAssertNil(TimeZone(secondsFromGMT: 18 * 3600 + 1))
156162
}
157163

158164
func test_initializingTimeZoneWithAbbreviation() {

0 commit comments

Comments
 (0)