Tom Tom - 2 months ago 32
Swift Question

Using public enums to control TimeZone in Swift 3

I've been updating some code to Swift 3.0. I was using Melvin Rivera's fantastic date extension for Swift 3.0. Now Melvin declares TimeZone as a public enum as follows:

public enum TimeZone {
case local, utc
}


Now I have trouble with my pre Swift 3.0 code that used some common TimeZone code. For Example:

let df = DateFormatter()
df.dateFormat = "MMM d, yyyy, hh:mm a"
df.timeZone = TimeZone(abbreviation: usersTimeZone)


Whenever I use such code I get a compiler error stating, "'TimeZone' cannot be constructed because it has no accessible initializers". What is the correct way to use the various TimeZone functions if TimeZone has been constructed as a public enum?

Answer

The error message says that TimeZone does not have any accessible initializers and it´s because it does not have any. TimeZone is an enum, you can type TimeZone.local or TimeZone.utc as it works today.

And for the initializers part you can read more about init here at Apples documentation site.

You can read more about enums on Apples documentation site.

Edit:
Update your code to the following:

let df = DateFormatter()
df.dateFormat = "MMM d, yyyy, hh:mm a"
df.timeZone = TimeZone(abbreviation: String(describing: Zone.local))

public enum Zone: String {
    case local
    case utc
}
  1. I renamed the TimeZone enum to Zone beacuase TimeZone is a reserved workd for the DateFormatter
  2. You need to pass a String value for TimeZone and that is what
  3. I have updated the code to Swift 3.0 syntax

.

Comments