adman adman - 11 months ago 50
Swift Question

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 =
var day1 =
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?

Answer Source

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

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


Will print out: