swiftdictionaryswiftlintforced-unwrapping

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


Solution

  • 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.