adman
adman

Reputation: 408

Swift - New Update gives optional issues

I just updated to Xcode 8 and Swift 3 on my iOS project. It now gives me problems in my app. Instead of giving me the right date and time elements, my label is displaying "Optional(2016)/Optional(09)/Optional(15)" instead of "2016/09/15". I haven't changed any code since the update and it was correct before. This is what I'm using:

let date = Date()
let calendar = Calendar.current
let components = (calendar as NSCalendar).components([.month, .year, .day, .hour, .minute, .second], from: date)
var day = components.day
var day1 = components.day
var year = components.year
var month = components.month
let hour = components.hour
let minutes = components.minute
let seconds = components.second


let timeString = "\(hour):\(minutes):\(seconds)"
var dateString = "\(year)/\(month)/\(day)"

Anybody know new optional syntax?

Upvotes: 1

Views: 938

Answers (3)

Rob
Rob

Reputation: 437592

If you want it formatted with leading zeros, it's probably easiest to use a DateFormatter:

let date = Date()

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"
let dateString = dateFormatter.string(from: date)

let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HH:mm:ss"
let timeString = timeFormatter.string(from: date)

If you really want to build these strings yourself, use String(format:):

let calendar = Calendar.current
let components = calendar.dateComponents([.month, .year, .day, .hour, .minute, .second], from: date)
let day = components.day
let year = components.year
let month = components.month
let hour = components.hour
let minutes = components.minute
let seconds = components.second

let timeString = String(format: "%02d:%02d:%02d", hour!, minutes!, seconds!)
let dateString = String(format: "%04d/%02d/%02d", year!, month!, day!)

Upvotes: 3

Rashwan L
Rashwan L

Reputation: 38833

You need to unwrap the variables with ! when you´re creating your timeString and dateString:

let timeString = "\(hour!):\(minutes!):\(seconds!)"
var dateString = "\(year!)/\(month!)/\(day!)"

print(timeString)
print(dateString)

Will print out:

6:0:25
2016/9/16

Upvotes: 2

vadian
vadian

Reputation: 285082

All properties of DateComponents have been turned into optionals for example

var day: Int? { get set }

But you can safely unwrap all properties which are specified in the components variable.

var day = components.day!

Upvotes: 3

Related Questions