Omit nil in string

58 Views Asked by At

I am practicing swift, and currently writing an easy function to show the schedule of the day. The return statement should only include busyDay if it contains a value. I hoped this would be done automatic, but it`s not.

func scheduleToday (date: String, day: String, numberOfMeetings: Int?) -> String {
    var meetingMessage = ""
    var busyDay: String!

    if var meetings = numberOfMeetings {
        if meetings > 4 {
           busyDay = "Today is a busy day!"
        }
       meetingMessage = "\(meetings) meetings"
    } else {
        meetingMessage = "no meetings today."
     }

    return "| \(date) - \(day) |   Good morning. \(busyDay) You have \(meetingMessage)."
}

If numberOfMeetings is 4 or less, the returned string says:

// | 17th of June - Wedensday |   Good morning. nil You have 3 meetings.
2

There are 2 best solutions below

0
On BEST ANSWER

You can just add an else statement to your if which sets budyDay to an empty string

if meetings > 4 {
    busyDay = "Today is a busy day!"
} else {
    busyDay = ""
}
0
On

You can use ternary operator which will assign empty string if numberOfMeetings is 4 or less and your code will be:

func scheduleToday (date: String, day: String, numberOfMeetings: Int?) -> String {
var meetingMessage = ""
var busyDay: String!

    if var meetings = numberOfMeetings {

        busyDay = meetings > 4 ? "\(meetings) meetings" : ""
        meetingMessage = "\(meetings) meetings"
    } else {
        meetingMessage = "no meetings today."
    }

    return "| \(date) - \(day) |   Good morning. \(busyDay) You have \(meetingMessage)."
}


let schedule = scheduleToday("1234", "8678678", 3)  // "| 1234 - 8678678 |   Good morning.  You have 3 meetings.""