user2636197 user2636197 - 16 days ago 4x
Swift Question

Swift function that return -> String returns Optional string

I have a function that calculates date:

func getFutureTime(_ timestamp: Double) -> String {
return "\( 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?


Optional is here

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

return "\(!) days"

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

return "\( ?? defaultDaysCount) days"

Or, best solution:

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