-1

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

Jkrist
  • 748
  • 1
  • 6
  • 24

2 Answers2

1

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.

holex
  • 23,961
  • 7
  • 62
  • 76
0

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))
Nikunj Damani
  • 753
  • 3
  • 11