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?

  • NSIndexPath and IndexPath in Swift 3.0
  • Swift Block value error
  • Use Legacy Swift Language Version - Xcode 8.2
  • Mutex alternatives in swift
  • Issue with UITableView: Action only works every second time
  • Registering for Push Notifications in Xcode 8/Swift 3.0?
  • 3 Solutions Collect From Internet About “Swift – New Update gives optional issues”

    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
    

    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!
    

    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!)