user2636197 user2636197 - 1 month ago 6
Swift Question

Swift function that return -> String returns Optional string

I have a function that calculates date:

func getFutureTime(_ timestamp: Double) -> String {
......
return "\(diffDateComponents.day) days"

}


I then call/set the funtion like:

futureTimeLabel.text = " \(Date().getFutureTime(timeStamp))"


But the time will show up as:

"Optional(4) days"


How can I saftley unwrap it so it doesnt print put as optional?

Answer

Optional is here diffDateComponents.day.

If you're really-really sure that day property would be a value, you may use diffDateComponents.day!, like:

return "\(diffDateComponents.day!) days"

Otherwise you can use ?? operator to set default value:

return "\(diffDateComponents.day ?? defaultDaysCount) days"

Or, best solution:

if let days = diffDateComponents.day {
    return "\(days) days"
} else {
    return "Default message, when there're no days in future. The End is nigh, I guess…"
}
Comments