user2636197 user2636197 - 1 year ago 92
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?

Answer Source

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…"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download