Jkrist
Jkrist

Reputation: 817

How to safely force unwrap time in dictionary

I have an issue. I have a dictionary type [String: Any]

my code that works is

dict["start"] = "\(start.hour!):\(start.minute!)"
if let end = end {
    dict["end"] = "\(end.hour!):\(end.minute!)"
}

But as I use swiftlint it throws me an error for force unwrapping. Value must be saved so if let is not good here :)

Upvotes: -1

Views: 176

Answers (2)

Nikunj Damani
Nikunj Damani

Reputation: 753

You can try the following demo code. I hope it will help you.

import Foundation

let calendar = Calendar.current

let dateComponents = DateComponents(hour: 12, minute: 20, second: 55)

func getHoursMinutesFrom(time: DateComponents) -> (hour: Int,minute: Int) {
    switch (time.hour, time.minute) {
    case let (.some(hour), .some(minutes)):
        return (hour,minutes)
    default:
        return (0,0)
    }
}

print(getHoursMinutesFrom(time: dateComponents))

Upvotes: 0

holex
holex

Reputation: 24031

that is mostly a semantic issue, but you could do something like this:

if let startHour = start.hour,
   let startMinute = start.minute {

    dict["start"] = "\(startHour):\(startMinute)"

    if let end = end,
       let endHour = end.hour,
       let endMinute = end.minute {

       dict["end"] = "\(endHour):\(endMinute)"
    }
}

...or something similar – as there are various ways in Swift to safely unwrap an optional.

Upvotes: 1

Related Questions